如何在使用Retrofit 2的unit testing期间创建retrofit.Response对象

在使用RxJava和Retrofit 2时,我正在尝试创建unit testing以覆盖我的应用程序何时收到特定响应。

我的问题是,使用Retrofit 2,我看不到一个很好的方法来创建一个不使用reflection的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 aResponse = null; try { Constructor constructor= (Constructor) 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); 

retrofit.Response类具有静态工厂方法来创建实例:

 public static  Response success(T body) { /* ... */ } public static  Response success(T body, com.squareup.okhttp.Response rawResponse) { /* ... */ } public static  Response error(int code, ResponseBody body) { /* ... */ } public static  Response error(ResponseBody body, com.squareup.okhttp.Response rawResponse) { /* ... */ } 

例如:

 Account account = ...; retrofit.Response aResponse = retrofit.Response.success(account); 

要么:

 retrofit.Response aResponse = retrofit.Response.error( 403, ResponseBody.create( MediaType.parse("application/json"), "{\"key\":[\"somestuff\"]}" ) ); 

这属于有效Java项目1:考虑静态工厂方法而不是构造函数