[英]@Captor and @Mock not creating objects with MockitoJUnitRunner
I am trying to write tests with the @Mock
and @Captor
annotations.我正在尝试使用
@Mock
和@Captor
注释编写测试。 However, the objects are not being created so I get NullPointerExceptions
.但是,没有创建对象,所以我得到
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'
}
I suspect you might be running your tests with JUnit 5, in which case the @RunWith
annotation doesn't work.我怀疑您可能正在使用 JUnit 5 运行您的测试,在这种情况下
@RunWith
注释不起作用。 Try using @ExtendWith(MockitoExtension.class)
instead.尝试使用
@ExtendWith(MockitoExtension.class)
代替。
Maybe related to your dependencies可能与您的依赖项有关
Can you update to use only spring-boot-starter-test
and remove all mockito
您可以更新为仅使用
spring-boot-starter-test
并删除所有mockito
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.