Today’s #AndroidTesting #Protip from +Stephan Linzner is about unit testing your code using  Mockito.

Writing unit tests is an important part of the Android development cycle as it encourages an incremental development approach and allows you to easily refactor your code, to continuously improve its quality. Unit tests are all about dependencies or about replacing dependencies with test doubles [0]. This allows you to run your tests in isolation as much as possible. But this raises the question on how you can efficiently create test doubles in your unit tests. One way to create test doubles on Android is to use Mockito [1]. Mockito is an open source mocking framework that offers a fluent and readable API which allows for both “state-based-testing” (stubbing) as well as “behavioral-testing” (verifications) [2].

To get started with Mockito in your unit tests you need to include the following dependencies in your build.gradle file [3]:

dependencies {
    androidTestCompile 'org.mockito:mockito-core:1.9.5'
    androidTestCompile ''
    androidTestCompile ''

To create a mock object in your tests you can either use Mockito’s static methods or use annotations. 

AccountManager mMockAccountManager = mock(AccountManager.class);

This will create a mock object for Android’s AccountManager class. A slightly cleaner approach is to use the @Mock annotation which greatly improves readability of the test code.

private AccountSelectionUi mAccountSelectionUi;

Stubbing methods with mockito follows the when/then pattern. To stub a method, call 


Here, AccountMananger.getAccounts() will return a fake account when it is called by the AccountsController. This lets you easily simulate dependencies, which can be very handy when dealing with framework classes. But Mockito also allows for verifying interactions.


In this case we verify that the showAccounts() method was called on the AccountSelectionUi with the expected array of Account objects. You can find the sample code for the AccountsControllerTest in this gist

Mockito can be a very handy tool when it comes to creating test doubles, but be aware of it’s limitations. Mockito can't create mocks for final classes and methods. Mockito’s philosophy is that tests should be easy to understand and low maintenance, therefore use mocks to stub  dependent methods of the unit under test and assert on the state of your unit rather than using behavioral verification which will more likely result in a fragile test. Have other Mockito tips? Let us know in the comments. Happy testing!

[3] To use Mockito in Eclipse, you need to copy the following dependencies into the /libs folder of your Android test project.

Shared publiclyView activity