首页 > 解决方案 > @Captor 和 @Mock 不使用 MockitoJUnitRunner 创建对象

问题描述

我正在尝试使用@Mock@Captor注释编写测试。但是,没有创建对象,所以我得到NullPointerExceptions.

考试:

@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"));
        }
}

我的依赖是:

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'
}

标签: javaspring-bootjunitmockito

解决方案


我怀疑您可能正在使用 JUnit 5 运行测试,在这种情况下@RunWith注释不起作用。尝试@ExtendWith(MockitoExtension.class) 改用。


推荐阅读