Mockito is my new love in the Android testing-sphere! (and it could be yours too)

So you finished your fancy new app and you have used dependency injection (DI) all over the place. But you almost forgot DI’s most important virtue: how easily you can test. Even if your app is not using any DI, you should keep reading. Mockito solves the most important obstacle for making unit tests: it easily mocks the dependencies in a test. This post is not aiming to be a complete guide to Mockito rather than a short into in case you haven’t heard of it before.

Setup

Add the repository to the project’s build file:

repositories {
jcenter()
}

and this line to your app’s build file:

testCompile "org.mockito:mockito-core:1.+"

You are done!

Mocking

Creating a fake dependency object is as easy as:

navigation = mock(Navigation.class);

or if you are a fan of injection you can use the @Mock annotation to do the same thing.

Testing

After you create your fake objects, all you have to do is to create the actual object and test it. Note that with the recent versions of Android Studio you get an example unit test with the creation of your project. We are creating all our fake objects in the @Before function and then use them in every @Test function we have.

private StartGamePresenter presenter; /* Subject Under Test */
private Navigation navigation;
private CurrentGame currentGame;

@Before
public void setup() {
currentGame = mock(CurrentGame.class);
navigation = mock(Navigation.class);
presenter = new StartGamePresenter(currentGame, navigation);
}

@Test
public void initGame() throws Exception {
presenter.initGame(1 /* round count */, 1 /* duration */);
verify(navigation).gotoPlayGameScreen(null);
}

Mockito offers many ways to verify the interactions (or no interactions) with its fake objects. In this snippet, we are using verify() to ensure that gotoPlayGameScreen() function was called with null as its calling parameter.

Further reading

Changing the how your fake objects behave is a really powerful feature that Mockito offers out of the box with the when()/thenReturn() function pair. You can choose the returned result for every call of your fake object.

More that the mentioned features, Mockito offers a lot more (like partial mocking) that you can read about in detail on their official page.

I am going to leave you with what I am pretty confident every developer enjoys to see: “All X tests have passed”.