我使用
Mockito
在我的应用程序中模拟一个 OkHttp
类。第一次模拟效果很好,我得到 "foo"
作为身体的回应,但第二次是空的。我试着调试它,看起来模拟正在工作,我不知道为什么它不能用于第二次调用。
我的测试:
@Test
void get500() throws IOException {
String responseMessage = "foo";
int responseCode = 500;
final OkHttpClient okHttpClient = mock(OkHttpClient.class);
final Call remoteCall = mock(Call.class);
final Response responseBuilder = new Response.Builder()
.request(new Request.Builder().url(url).build())
.protocol(Protocol.HTTP_1_1)
.code(responseCode).message("").body(
ResponseBody.create(
responseMessage,
MediaType.parse("application/json")
))
.build();
when(remoteCall.execute()).thenReturn(responseBuilder);
when(okHttpClient.newCall(any())).thenReturn(remoteCall);
MyHttp myHttp = new MyHttp(okHttpClient);
ResponseServer response = myHttp.get("http://url.com");
Assertions.assertEquals(response.getBody(), responseMessage);
}
这是
MyHttp
课:
public class MyHttp {
protected final OkHttpClient client;
public MyHttp(OkHttpClient client) {
this.client = client;
}
public ResponseServer get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = client.newCall(request).execute();
String responseBody = Objects.requireNonNull(response.body()).string();
Assertions.assertEquals(response.getBody(), "foo");
Response response2 = client.newCall(request).execute();
String responseBody2 = Objects.requireNonNull(response2.body()).string();
Assertions.assertEquals(response2.getBody(), "foo"); // response is empty
}
}
编辑:
如下所示的模拟响应但没有用:
Response mockResponse = mock(Response.class);
when(mockResponse.request()).thenReturn(new Request.Builder().url(url).build());
when(mockResponse.protocol()).thenReturn(Protocol.HTTP_1_1);
when(mockResponse.code()).thenReturn(responseCode);
when(mockResponse.message()).thenReturn("");
when(mockResponse.body()).thenReturn(
ResponseBody.create(
responseMessage,
MediaType.parse("application/json")
));