如何模拟OkHttpClient请求到外部URL?

时间:2020-05-21 17:30:13

标签: unit-testing mocking okhttp

我的服务中包含以下代码:

public String requestValue() {
  Call call = okHttpClient.newCall(new Request.Builder().url("external-url").build());
  Response response = call.execute();
  return response.body().string();
}

如何在Junit测试中模拟该调用的结果?

public void testRequestValue() {
  // TODO mock http response
  String result = myService.requestValue();
  assertEquals("value", result);
}

注意:Mockito的幼稚解决方案不起作用。 Mockito.eq不会在Request个对象上触发(似乎Request.equals对于相同的请求提供了不正确的结果)。

Request request = new Request.Builder().url("external-url").build();
Response response = new Response.Builder()
  .request(request)
  .protocol(Protocol.HTTP_2)
  .code(200)
  .message("")
  .body(ResponseBody.create("value", MediaType.get("application/json")))
  .build();

Call call = Mockito.mock(Call.class);
Mockito.when(call.execute()).thenReturn(response);
Mockito.when(okHttpClientMock.newCall(Mockito.eq(request))).thenReturn(call);

1 个答案:

答案 0 :(得分:0)

您可以使用wiremockokhttp提供的MockServer