Every developer knows that testing software can take a lot of time. Being the brilliant industrious individuals that we are, engineers invented multiple ways to test software. Unit testing is just one part among others such as functional testing, integration testing, and acceptance testing.
In this blog, we will go over how to write unit tests for Android using the latest tools and libraries. In this example, I am leveraging JUnit4 and Mockito.
What is Unit Testing?
Tests the smallest functionality of a feature. This is generally a function with a single responsibility. Unit tests shouldn’t be concerned with outside dependancies and if they exist in the code, they should be mocked or stubbed. You generally test the public interface of your code which should call on any and all unaccessible implementation hidden within the class.
The goal is to create a test that is relatively simple, easy to debug, fast to execute, and validates that your unit of functionality works within it’s own encapsulation before it is used by another object.
Example : Buying a Drink
We have a Patron, Matt, who enters a cafe and buys a cold, refreshing Nuka Cola. To unit test the functionality of buying a drink, we will mock both the Cafe and DrinkInterface because the implementation of these objects are largely irrelevant to testing the Patron class.
We create Matt to test the Patron class. PatronHelper is a child of the Patron class which helps reveal unaccesable properties for our tests.
We also create a mocked Cafe object. It emulates the class without knowing about the implementation.
@Before is called before every test.
Creating a mocked Drink
Creates a mocked or dummy DrinkInterface object without copying any of the functionality.
When getCost is called, it will return the value of cost.
When getName is called, it will return the value of targetDrinkName.