【发布时间】:2021-12-02 22:20:07
【问题描述】:
我正在尝试在我的 Spring Boot 应用程序中将 okhttp 与 Mockito 一起使用,但我总是在行时收到 NullPointerException
httpClient.newCall(request).execute()
我们如何将 Mockito 与 okhttp 一起使用?
@Component
public class HStatus {
@Autowired
private OkHttpClient httpClient;
public int HCheck() throws URISyntaxException, IOException {
String url = new URIBuilder("Some URL").build().toString();
Request request = new Request.Builder().url(url).get().build();
try (Response resp = httpClient.newCall(request).execute()) {
return resp.code();
}
}
在junit中,我正在尝试做-
@RunWith(MockitoJUnitRunner.class)
public class HStatusTest {
@InjectMocks
private HStatus hStatus;
@Mock
private OkHttpClient httpClient;
@Test
public void TestHCheck_Should_Return_200_StatusCode() throws URISyntaxException, IOException {
Response resp = new Response.Builder()
.request(new Request.Builder().url("SOME URL").build())
.protocol(Protocol.HTTP_1_1)
.code(200).message("")
.build();
Mockito.when(httpClient.newCall(ArgumentMatchers.any()).execute).thenReturn(resp);
// Getting NullPointer at this call -> httpClient.newCall(ArgumentMatchers.any()).execute
int statusCode = hStatus.HCheck();
assertEquals(200, statusCode);
}
}
【问题讨论】:
-
请更新更多上下文,包括周边代码和测试代码。
-
另外,okhttp 源代码是可用的。它有自己的测试。为什么要重复它们?也许您应该改用 rest-assured 或 wiremock 来测试实际的服务器?
-
你应该通过服务器返回一个模拟响应,而不是来自客户端执行github.com/square/okhttp/tree/master/mockwebserver
标签: java spring-boot nullpointerexception mockito okhttp