Mock Retrofit service using MockRestAdapter and Espresso 2.0 (No Mockito)
Note:DON’T DO THIS! check the end of the post to know why.
I will not use mockito because it give me so much errors, when we will use
Android Support Test: runner, rules and espresso.
jUnit4: as base tests.
assertj-android: because is so cool.
retrofit-mock: to mock our services.
You need to add as dependency:
The project will use Order.get(“id”) to get the observable, inside of it we will call the retrofit reacted
service to get the data and return it (process it before if we need to, por ex save into shared preferences).
The idea is to override that service instance that Order have with the mocked one created using MockRestAdapter
from retrofit guys.
We will need:
A normal retrofit service interface (OrderService).
A mock service that returns what we want (MockedOrderService).
Everytime before the activity is created on the tests we should replace the service instance on the app
with the mocked one.
Note it uses @VisibleForTesting from support-annotations notation to show that it should be private but is public to allow
us to change it´s value on tests.
And then our tests will look like:
Note: Be careful if your activity use the services onResume or onStart because then we will need to start the activity
JUST after we mocked the services (The last example mock it after becuase @Rule starts activity automatically).
Then we need to put true, false in the ActivityTestRule constructor to avoid that and start manually.
Thansk to Retrofit guys for everything!.
If you end trying to do something like this maybe you have a terrible not testeable code structure, so please don’t do it. It will be hard to change and really really hard to understand.
At the end I removed every espresso test and start using MVP in all the project,
then I can run my tests just on JVM (Yeah, no more android emulator).
Check Mockito or Powermock for mocking the api responses, and if you try and you can’t again is posible that you have a terrible code structure.
Daniel Gomez Rico
The findings and tips records of an Android-iOS-TheWholeShabang group