在使用RxJava和Retrofit 2时,我试图创建单元测试以覆盖当我的应用程序接收特定响应时的情况。
问题在于,使用Retrofit 2时,我无法找到一种好的方式来创建retrofit.Response对象,而不使用反射。
@Test
public void testLogin_throwsLoginBadRequestExceptionWhen403Error() {
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.get();
requestBuilder.url("http://localhost");
Response.Builder responseBuilder = new Response.Builder();
responseBuilder.code(403);
responseBuilder.protocol(Protocol.HTTP_1_1);
responseBuilder.body(ResponseBody.create(MediaType.parse("application/json"), "{\"key\":[\"somestuff\"]}"));
responseBuilder.request(requestBuilder.build());
retrofit.Response<LoginResponse> aResponse = null;
try {
Constructor<retrofit.Response> constructor= (Constructor<retrofit.Response>) retrofit.Response.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
aResponse = constructor.newInstance(responseBuilder.build(), null, null);
} catch (Exception ex) {
//reflection error
}
doReturn(Observable.just(aResponse)).when(mockLoginAPI).login(anyObject());
TestSubscriber testSubscriber = new TestSubscriber();
loginAPIService.login(loginRequest).subscribe(testSubscriber);
Throwable resultError = (Throwable) testSubscriber.getOnErrorEvents().get(0);
assertTrue(resultError instanceof LoginBadRequestException);
}
我尝试使用以下代码,但它创建了一个OkHttp响应而不是Retrofit响应。
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.get();
requestBuilder.url("http://localhost");
Response.Builder responseBuilder = new Response.Builder();
responseBuilder.code(403);
responseBuilder.protocol(Protocol.HTTP_1_1);
Response.<Account>error(....)
。 - nhaarmanretrofit.Response<Account> aResponse = retrofit.Response.success(account);
我得到了一个类转换异常(请注意,我的版本中单词“success”拼写正确)。 - Graham Smithjava.lang.ClassCastException: com.a.project.MyObject无法转换为retrofit.Response
。 - Graham Smith