我在应用程序中使用Mockito
模拟OkHttp
类。第一次mock运行良好,我在body中得到"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")
));
1条答案
按热度按时间gmxoilav1#
我复制了您的示例,但做了一些更正(您的代码段有编译错误)
我的部分mavenpom.xml:
MyHttp类:
测试类