Test your retrofit2 API call

Fijar Lazuardy
Inside PPL B7
Published in
3 min readMay 11, 2020

It’s no little-known fact that unit testing is a crucial part of development, not only in Android but in pretty much any software development field. The ideal app should have 100% test coverage.

Unit tests are supposed to be small, quick to write and fast to execute. They should also test isolated parts of your code’s logic.

This begs the question, how do we test our API calls without actually making calls to the network?

Introducing MockWebServer

MockWebServer is a library made by Squareup (the guys behind OkHttp and Retrofit) used to fake API calls for testing purposes. You would load in a JSON file that you’ve hardcoded into your app, and enqueue that on an instance of MockWebServer.

After doing that, the server will now know what response to return on the next request it receives.

What are we testing here?

In my experience, you’d use this to test the parsing of a response into a data class (if you’re using automatic POJO parsing with Gson, Jackson, etc.), or your manual deserialisation of a response into said data class.

Add the Dependencies

Add this to your app/build.gradle file.

  • testImplementation ‘com.squareup.okhttp3:mockwebserver:4.3.1’

Add the JSON File

Under your app directory, create another folder called resources if there isn’t one already. Under here, you can put your sample responses here, such as this one.

The above code is the same as a response you’d get from the JSONPlaceholder API.

What you can do is make an API call to your own API you want to test (via the browser or Postman), copy that into a separate file you’ll add to your resources folder, and replace any sensitive data such as API keys.

Create a MockResponseFileReader

You’ll need a way of reading your mock API responses during your tests. You can use a helper class I’d like to call MockResponseFileReader.

This allows you to create an instance of MockResponseFileReader, passing in the path of your mock JSON file, then you’ll be able to grab the content of it like so which you’ll need to pass into your MockWebServer instance.

MockResponseFileReader("200_ok_login.json").content

Testing with MockWebServer

That’s the set up pretty much done. Now let’s get to the actual test.

In your test class, create an instance of MockWebServer like so.

private val server = MockWebServer()

Set up your Before and After methods to start and shutdown the webserver, as well as create a Retrofit or whatever you’re using to make calls to that server.

@Before
fun setUp() {
server.start(MOCK_WEBSERVER_PORT)

val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val loginResponse = Retrofit.Builder()
.baseUrl(server.url("/")) .client(OkHttpClient.Builder().addInterceptor(interceptor).build())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(LoginResponse::class.java)
}

@After
fun shutdown() {
server.shutdown()
}

And then you can “test” you retrofit2 call

@Test
fun `LoginResponse API parse correctly`() {
server.apply {
enqueue(MockResponse().setBody(MockResponseFileReader("200_ok_login.json").content))
}
jsonRepository.observeDoublePlaceolder()
.test()
.awaitDone(3, TimeUnit.SECONDS)
.assertComplete()
.assertValueCount(1)
.assertNoErrors()
}

That’s it, there are many other ways to implement it, but it’s one of them, go and give it a shot. Cheers!

--

--