Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何将OkHttpClient请求模拟为外部URL?_Unit Testing_Mocking_Okhttp - Fatal编程技术网

Unit testing 如何将OkHttpClient请求模拟为外部URL?

Unit testing 如何将OkHttpClient请求模拟为外部URL?,unit-testing,mocking,okhttp,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 testRequest

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

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
为相同的请求提供了不正确的结果)

您可以使用或提供的MockServer

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);