如何创build一个retrofit.Response对象在unit testing与改造2

在使用RxJava和Retrofit 2时,我正在尝试创buildunit testing来覆盖我的应用何时收到特定响应。

我遇到的问题是,使用Retrofit 2我看不到使用reflection创buildretrofit.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); } 

我已经尝试使用以下,但是这创build一个OkHttp响应与改造响应。

  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); 

Solutions Collecting From Web of "如何创build一个retrofit.Response对象在unit testing与改造2"

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

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

例如:

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

要么:

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

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