gpt4 book ai didi

java - @Captor 和 @Mock 不使用 MockitoJUnitRunner 创建对象

转载 作者:行者123 更新时间:2023-12-04 08:51:32 25 4
gpt4 key购买 nike

我正在尝试使用 @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) 反而。

关于java - @Captor 和 @Mock 不使用 MockitoJUnitRunner 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64077805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com