Eve
Eve

Reputation: 1238

Android Unit test API calls with Retrofit2

I haven't done any testing in Android, so please bear with me if this seems a stupid question. I'm developing an app which makes a lot of network calls from a restful API service. To make the network calls, I'm using Retrofit2 and RxJava.

What would be the best practice/framework to just test if these calls are working? I've started to read the Google Codelab for testing which uses Junit4 and Mockito, but I don't want to do any clicking in the UI to start a test currently, just checking for different API versions which calls are supported or not.

Upvotes: 1

Views: 1590

Answers (1)

Diolor
Diolor

Reputation: 13450

Here some steps for you that I am using:

  • Use mockito & junit4, for sure :)
  • I avoid UI tests for these cases
  • Pass your retrofit Api as a parameter to a class that you want to test
  • In the test create a mock retrofit api, pass this one as a parameter so you can choose what you want your "Api" to return e.g. objects or errors (see Mockito.when())
  • Use RxJava's TestSubscriber to test a method e.g. Observable<Location> getLocationFromApi()
  • Avoid threading in your testing class (e.g. like .observeOn(mainThread())). If inevitable use awaitTerminalEvents in TestSubscriber. If there is no terminal even rethink your test

General tips:

  • Try to modularize your code so each class has few functionality -> easier to test.
  • Be patient and don't expect to write tests for e.g. 5% of your code in just one week :) It's a slow process regardless team size

Upvotes: 4

Related Questions