Mockito — The Basic

Mockito — The Basic

Just recently at Wellthy, where I work as Sr. Android engineer, we decided to write Unit test and mock objects. I decided to write up on the discussion we had as a tutorial on creating dependencies (collaborators) for unit testing. We discuss mock objects and give some simple examples that illustrate the usage, and the advantages and disadvantages approach in upcoming articles.

Why mockito —

One of the best mocking and behaviour verification framework. It lets you write a beautiful test with clean and simple API. Tests are very readable and they produce very clean verification errors.

There are other alternatives also available for mockito. One of them I know i.e. EasyMock.

When I started writing test for mockito the first question that popped in my head was why there are two separate dependencies Mockito-All and Mockito-Core.

Mockito all is packaged with Hamcrest and Objenesis but “mockito-all” distribution has been discontinued in Mockito 2.*. Better to go with “mockito-core”.

How to get started —

Recommended way of getting Mockito is declaring a dependency on “mockito-core” library using your favourite build system. With Gradle one can do:

repositories { jcenter() }
dependencies { testCompile "org.mockito:mockito-core:1.+" }

You can check here to find out latest release of mockito.

Mockito provides several ways to create mock object:

  • Using the static mock() method.
  • Using the mock annotaion.

If you use the @Mock annotation, you must trigger the creation of annotated objects. The MockitoRule allows this. It invokes the static method MockitoAnnotations.initMocks(this)to populate the annotated fields. Alternatively you can use @RunWith(MockitoJUnitRunner.class).

Take this simple example:

import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
// using static imports  greatly improves readability of your test, // you should use it.
import static org.mockito.Mockito.verify;

public class MockitoTest {

    // Tells Mockito to mock this View class object
    // Note: don't get confused with Android Widget View
    @Mock View view;
    // Tells mockito to create the mocks based on @Mock annotation
    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

    public void testPresenter(){
        // Instantiate class under test using created mock
        Presenter presenter = new Presenter(view);
        // Execute some code of class under which internally calls           method of mock object
        // Verify that the foo method was called on the View mock 

So to Quick Recap:

  • Use mockito-core instead of mockito-all.
  • Use mockito for behaviour verification (BDD).

Happy coding and writing about coding!
If you found this helpful, click the 💚 below. Stay tuned for more on Mockito.