Android Local Unit Testing (Part 2)

[no_toc]

Introduction
In Part I, I discussed setting up the testing environment. In this post I will discuss how to actually write unit tests. As described in part I, we are specifically focused on local units tests and not on-device testing.
 
Simple JUnit tests
The simplest example of unit testing would be using JUnit to test a simple utility class. We are also using AssertJ to make code more readable. Assuming that we have a utility class that can do simple addition below:
 
Screen Shot 2015-07-27 at 12.57.49 PM
 
The following is a simple JUnit4 test:
 
Screen Shot 2015-07-27 at 1.06.51 PM
 
Tests Using Resources
Tests using resources are basically the same, but reference the R file. Note that you cannot actually retrieve the resources since the Android library stubs all Android classes. Same example as above but with resources:
 
Utility class:
 
Screen Shot 2015-07-27 at 1.00.04 PM
 
The following is a test class:
 
Screen Shot 2015-07-27 at 1.00.48 PM
 
Mocking Android Classes
Now I want to take things a little further and try to use an Android class (Context in this example). As discussed in Part 1, the Android Testing Support Library stubs all Android classes. That means that if you try to access any Android class, you will get an exception. The solution is to mock whatever classes/methods you are using. In our example, we will be mocking the Context.getString() method with Mockito. To make the code more concise, we are using the Mockito test runner instead of the standard JUnit4 runner, but this is not required.
 
Utility class:
 
Screen Shot 2015-07-27 at 1.01.40 PM
 
The following is a test class (without imports):
 
Screen Shot 2015-07-27 at 1.01.49 PM
 
Next Steps: Android UI Testing Frameworks
 
In these posts, I discussed the basic foundations of Android unit testing (which isn’t much different from standard Java), and how to test utility classes. Now, if we want to take things a little further and start testing UI, it gets complicated. Because UI components in Android rely heavily on the Android classes, it would get harder and harder to mock specific classes as the complexity of the code being tested increases. There are several options to explore further if UI testing is desired. The advantage of using these libraries is that they would provide mock functionality for many Android classes, making testing easier and mocking un-necessary.

All of these have different types of issues that need to be researched:
– On-device testing with the Android Testing Support Library, Calabash or the new Google Test Lab
Robolectric library – this would be my primary choice. HOWEVER, version 2 of Robolectric is pretty old, and version 3 is still in beta. Additionally, in my testing, Robolectric does support well the Android AppCompat and ActionBar activities.
Robotium – haven’t tried it

Chat Support