How to write testable code for your Android project
Recently I was working on an Android project that invokes a pop up window, which has date time picker as in iOS devices as shown below:
The library that I was using has great features as what I wanted and I’m happy to find one as I don’t have to develop the feature from scratch and it saves development time. Thanks to all the great souls who love to open source their projects.
Checkout the library here : https://github.com/florent37/SingleDateAndTimePicker
However, the library doesn’t have exact features that I was looking for, namely:
1. Limit the hour selection from 7am -11pm
2. Set minimum day to next day 7am
There are two workarounds for this problem. The first is to inherit by extending the library class to have the desired output or the second, simply give a formatted empty string as output when above conditions met. I choose the latter and started coding immediately as shown below:
To summarise the above code overrides onDateChanged interface method, which has a date as input parameter and formats the date to a human-readable string. That’s it and job well done.
Well not exactly. As a good development practice, one should write unit tests for the code that written in order to pass all the conditions during system under test.
To read more about unit test, please read here:
https://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters
As you have already realized, the above code is non-testable for the two conditions that I have mentioned earlier. It is difficult to write unit tests with the above code.
Well, it’s time to re-think and rewrite a clean testable code. First, we’re going to write two methods to satisfy the two conditions:
- Method to check given date is before minimum date
2. Method to check given date within the acceptable range (7 am — 11 pm)
Now, invoke these methods inside onDateChanged to validate the selected date and return an empty string if the conditions are true:
There you go! A clean testable code. Now let’s write a unit test to check if given date is before minimum date.
Likewise, we can write unit test for other methods in this class to test all conditions that are required to pass the test suites.
Unit test help developers alike to rethink and rewrite the code in order to make the code testable and robust.Writing unit test is easy if your code is clean and testable.
Happy Coding!
PS: Adopt MVP Architecture to improve code testability