我的服务中包含以下代码:
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);