【问题标题】:@Captor and @Mock not creating objects with MockitoJUnitRunner@Captor 和 @Mock 不使用 MockitoJUnitRunner 创建对象
【发布时间】:2021-01-12 14:20:13
【问题描述】:

我正在尝试使用 @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'
}

【问题讨论】:

    标签: java spring-boot junit mockito


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      可能与你的依赖有关

      您能否更新为仅使用 spring-boot-starter-test 并删除所有 mockito

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-23
        • 2020-12-20
        • 1970-01-01
        • 2017-06-14
        • 2020-02-17
        相关资源
        最近更新 更多