@Captor and @Mock not creating objects with MockitoJUnitRunner

Viewed 310

I am trying to write tests with the @Mock and @Captor annotations. However, the objects are not being created so I get NullPointerExceptions.

The test:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
    @Mock
    HttpClient.Builder builder;
    @Mock
    HttpClient client;
    @Captor
    ArgumentCaptor<HttpRequest> request;

    MockedStatic<HttpClient> staticClient;

    public MockedStatic<HttpClient> server() {
        // Set up mock server
        staticClient= Mockito.mockStatic(HttpClient.class);
        staticClient.when(HttpClient::newBuilder).thenReturn(builder);
        when(builder.build()).thenReturn(client);
        return staticClient;
    }

    @Test
    public void shouldCallService() throws IOException, InterruptedException {
        try (MockedStatic<HttpClient> ignored = server()) {
            HttpResponse response = mock(HttpResponse.class);
            when(client.send(any(), any())).thenReturn(response);
            when(response.body()).thenReturn("response");

            TestService service = new TestService();
            service.callService();

            verify(client).send(captor.capture(), HttpResponse.BodyHandlers.ofString());
            assertThat(captor.getValue().uri().getPath(), equalTo("localhost:8081"));
        }
}

My dependencies are:

implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.mockito:mockito-core:3.5.11'
testImplementation "org.mockito:mockito-inline"
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.mockito', module: 'mockito-core'
}
2 Answers

I suspect you might be running your tests with JUnit 5, in which case the @RunWith annotation doesn't work. Try using @ExtendWith(MockitoExtension.class) instead.

Maybe related to your dependencies

Can you update to use only spring-boot-starter-test and remove all mockito

Related