java - @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'
}
解决方案
我怀疑您可能正在使用 JUnit 5 运行测试,在这种情况下@RunWith
注释不起作用。尝试@ExtendWith(MockitoExtension.class)
改用。
推荐阅读
- kubernetes - Ansible:从 gce_container_cluster 获取 api_token
- sqlite - 当 sqlite 仅包含数字时,如何让它保留字符串类型?
- r - 在 R 中使用 lines() 时线没有出现在绘图上
- vue.js - 从多个子组件Vue js中获取数据
- java - 如何查看正确的月份而不仅仅是 2 月(已关闭)
- javascript - 如何在mongodb中的.aggregation之后插入一个数组作为新文档?
- git - git log colorify GPG签名验证状态
- laravel - 创建自定义服务提供者的最佳方式是什么时候?
- zfs - ZFS 我可以在非扩展池上用较小的磁盘替换磁盘吗?
- python - 验证用户密码的随机选择的字符