Instrumentation Tests with Dagger2, Retrofit2, RxJava2 and MockWebServer — Android
It has been a while since I wrote a blog, I got some time to write about UI testing, which I found useful. When I started writing test cases, I was sure to use DI, mock server response, it took a while to come with a fully functional flow. I’ll share it here step-by-step.
Refer my blog for Unit tests in Android
NOTE: Before starting, if you are not familiar with Dagger2, Retrofit2, RxJava2 and Kotlin. Pls, Stop! there are plenty of resources available on the internet, have some knowledge, then continue with this flow.
Step 0: App Demo
Let’s begin,
It’s a simple app, once you launch, it’ll hit an API call based on the success or failure, we’ll update the text view.
Step 1: MockWebServer
As the name suggests, it mocks your web server. It’s a handy tool from Square.
Step 2: Dagger2
I’ve made a function getAppComponent() in app’s Application class to return DaggerAppComponent,
Step 3: Create Dagger2 Module, TestApplicationModule.kt
Nothing too special, the above module will generate the retrofit instance with the following base URL.
http://localhost:8080/
Yes, all our API calls in test cases will now point to the local machine, not to the real server.
Step 4: Create a new application class extending the old application class inside the test folder and override getAppComponent() by replacing with above TestApplicationModule in the dagger component.
Step 5: Create a custom AndroidJUnitRunner for our test cases, it’ll place our UiGitHubDelegate class name in the newApplication() and set the StrictMode.
change default test runner with yours in app/build.gradle
android {
...
testInstrumentationRunner "com.audhil.medium.samplegithubapp.runner.UiRunner"
...
}
For reference:
Step 6: MockServerDispatcher, it dispatches API fake responses based on the request path for our test cases. I’ve kept it as simple as below,
Step 7: Write the TestCase
points to note,
- init MockWebServer() at port 8080, and shutDown after completion of test cases.
- val rule = ActivityTestRule(DummyActivity::class.java, false, false)
when we pass the 3rd argument(launchActivity) as false, it is our responsibility to start the activity for our test cases.
3. intent.putExtra(ConstantsUtil.MOCK_URL,”URL”)
each test case will pass the respective URL to the activity, our final URLs be like,
http://localhost:8080/todos/1
or
http://localhost:8080/jack%20and%20jill%20URL
and our MockServerDispatcher will dispatch respective response the network calls.
Voila! below the report of our test cases
complete source code is available in github
Bonus,
If you want to be familiar with MVVM, DataBinding, Dagger2, RxJava2, Retrofit2, Android Arch Components etc. Pls, refer to the source code.
If you like this article, don’t forget to clap! that keeps me motivated!
That's it, Happy Coding!