Manually Create a Retrofit/OkHttp Response for Testing

Posted by in Software

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:

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:

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:

Fairly simple.


A little experiment: If you find this post and ad below useful, please check the ad out 🙂