Android Clean Code — Part 2
Test Driven App Development in Android
Interactor Class of Android Clean Code and its unit testing
Having understood how to test the Android Activity in part 1 of the series, let’s look at the Interactor and its unit testing.
What is the work of Interactor?
Retrieve the data from the data sources like local DB, web service and content provider.
In this example, Interactor is expected to fetch the list of present or future flight trips. Let’s look at the Interactor class
Interactor implements the InteractorInput interface defined in part 1. In HomeInteractor class, method fetchHomeMetaData takes care of data retrieval and based on the certain logic (whether the trip is the past or future trip) have delegated the data retrieval work to another class called FlightWorker.
How do Interactor talks to Worker?
Using the interface WorkerInput.
Why we use interfaces?
Loose Coupling — classes talks to each other using the interfaces, during the unit testing, we will be able to mock the other dependent classes without much of a sweat.
What is the need for Worker?
- If the task is simpler, you can have all the work done by the Interactor itself.
- You foresee that the task can be reused somewhere else in the app, move it to the worker.
When Interactor needs to perform more than one task, having multiple workers to execute each one of the task is the recommendation of clean architecture — confirming SOLID principle.
Unit Testing
Let’s test whether Worker is called and the correct method is invoked. How to test this scenario?
We don’t need a real worker, let’s create a spy.
Note that you cannot test Interactor without Presenter instance and we don’t the want real instance of Presenter. Let’s create a spy for Presenter and use it when needed.
With test setup work is completed, write a test method to check if the worker is called with right inputs.
Next, with the Worker is unit tested, let’s write the code to test whether
- presenter method is called
- with right values
By this time, you may have realised how powerful is Android Clean Code design pattern — it helps you unit test the app piece by piece, without hardwiring dependencies. You can test whether the method is called and also if the parameters have the right values and you can repeat this drill in every public method of the class.
I suggest you clone the example project, if not done already and before we close this exercise, run the test cases with code coverage(Android Studio → Menu →Run →Run with coverage). Check the code coverage of the Interactor class.
If you are already started worrying about the boilerplate code of this pattern, do not worry, we have code scaffolding done for you from Android Studio, will be explained in one of the future posts.
What’s next? Presenter in the next post.
————————————————— — — — — — — — — — — — — — — —
Acknowledgments
- Logo by Suresh C R
- Article Inspired from Clean Swift