'Error: Static mocking is already registered in the current thread

Junit test case getting failed:

existing static mocking registration must be deregistered

Test class:

@RunWith(MockitoJUnitRunner.class)
public class DeleteReportServiceTest {

    @InjectMocks
    private ReturnCheckController returnCheckController;

    @Mock
    MockedStatic<DigitalGatewayRESTClient> mockDigiGateway;

    @Before
    public void setUp() throws Exception {
        this.returnCheckController = new ReturnCheckController();
        this.mockDigiGateway = Mockito.mockStatic(DigitalGatewayRESTClient.class);
    }

    @Test
    public void testdeleteReport() throws Exception {
        String input = "{\"clientId\": \"1\", \"applicationId\": \"9010\"}";
        String response = "{\"success\":true,\"successText\":\"Manual adjustment record deleted\"}";
        String expected = "{\"status\":200}";
        JSONObject returnJson = new JSONObject(response);
        mockDigiGateway.when((Verification) DigitalGatewayRESTClient.getDGRESTConnection(Mockito.any())).thenReturn(returnJson);
        String actual = returnCheckController.deleteReport(input);
        Assert.assertNotNull(actual);
        Assert.assertEquals(expected, actual);
    }

    @After
    public void after() {
        mockDigiGateway.close();
    }
}

Closing the static mocking still am getting the error.



Solution 1:[1]

You can NOT use @Mock and MockedStatic at same time. Instead, if you want to stub static method of DigitalGatewayRESTClient, you should create a MockedStatic<DigitalGatewayRESTClient> additionally, like this:

private MockedStatic<DigitalGatewayRESTClient> mockedStaticDigiGateway;

Then initialize mockedStaticDigiGateway:

@Before
public void setUp() throws Exception {
    this.mockedStaticDigiGateway = Mockito.mockStatic(DigitalGatewayRESTClient.class);
    // other setup...
}

and modify your test case, stub mockedStaticDigiGateway.when... instead:

@Test
public void testdeleteReport() throws Exception {
    // arrange ...
    
    mockedStaticDigiGateway.when((Verification) DigitalGatewayRESTClient.getDGRESTConnection(Mockito.any()))
        .thenReturn(returnJson);

    // assert...
}

Finally, close mockedStaticDigiGateway after test is finished:

@After
public void after() {
    mockedStaticDigiGateway.close();
}

I think it will work correctly although one year passed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1