Skip to content

Manually Create a Retrofit/OkHttp Response for Testing

September 21st, 2015 - Software(1 min)

I’ve got a method in an use case which requires a Retofit Response object as parameter and I need to test it. Now, I can use the Retrofit itself and build one with the network, but it would require the full android shebang.

I’ve opted instead for building a Retrofit Response manually. My method is testing headers, so I’ll need to build a Response with headers. The Response method to do this is:

public static <T> Response<T> success(T body,
    com.squareup.okhttp.Response rawResponse) {
    return new Response<>(rawResponse, body, null);
  }

A note: Where you see Response , it’s actually retrofit.Response. The OkHttp counterpart is prefixed: com.squareup.okhttp.Response.

So, in turn I require an OkHttp Response object. OkHttp uses the builder pattern for everything, so, to make my life easier, I’m preparing the builder in a setUp() method:

private com.squareup.okhttp.Response.Builder mOkHttpResponseBuilder;

@Before public void setUp() {
    HttpUrl mHttpUrl = new HttpUrl.Builder()
            .scheme("https")
            .host("example.com")
            .build();
    Request mRequest = new Request.Builder()
            .url(mHttpUrl)
            .build();

    // Prepare the builder with common stuff.
    mOkHttpResponseBuilder = new com.squareup.okhttp.Response.Builder()
            .request(mRequest)
            .protocol(Protocol.HTTP_1_1)
            .code(302);
}

Here, you can see several elements:

  • A HttpUrl object which defines the URL used (builder pattern)
  • A OkHttp Request object which requires mHttpUrl (bulder pattern)
  • The OkHttp Response.Builder object which requires the Request object defined above and a protocol.

Now, we can use the builder over and over:

com.squareup.okhttp.Response okHttpResponse = mOkHttpResponseBuilder
    .addHeader(LoginUseCase.LOCATION_HEADER, LoginUseCase.LOGIN_SUCCESSFUL)
    .build();

Response<String> response = Response.success(null, okHttpResponse);
Assert.assertTrue(new LoginUseCase().isLoggedIn(response));

Fairly simple.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: