Creating Mocks and Setting up Mockito Unit Tests

Overview

  • You can create mocks either by using the API or by annotation
  • You set up Mockito based unit tests by either using the Mcokito JUnit runner, including a JUnit 4 rule or by the API

Creating Mocks

Creating mocks programmatically

You can create mocks programmatically by supplying an interface or class to the mock() method:

MyService mockService = Mockito.mock(MyService.class);

To do this, ensure you import org.mockito.Mockito and the type you want to mock.

Creating mocks by annotation

You can create mocks by annotation by annotating the type(s) to be mocked in your unit test, which will be included as member variables, with @Mock:

import org.mockito.Mock;


public class MyTest {

  @Mock
  private MyService mockService;

                :

}

In order for this to work, you must ensure that Mockito’s runtime has been initialised correctly by doing one of the following to initialise the annotations framework:

  • making an explicit API call to do it
  • embedding the Mockito JUnit Rule
  • using the Mockito JUnit test runnner

Annotation initialisation via API call

If you’re initialising the annotations framework programmatically, call the initMock method. Doing this in an @Before-annotated method will ensure it’s always done before any test executes so your mocks are ready for each test:

import org.mockito.MockitoAnnotations;
import org.junit.Before;


public class MyTest {

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

            :
}

Notice that you pass in the class which is to be introspected (looked in) which has the mock declarations.

Annotation initialisation via JUnit Rule

Alternatively, you can use a JUnit 4 rule instead. Just use the Mockito rule as a public member variable:

import org.mockito.junit.MockitoRule;
import org.junit.Rule;


public class MyTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule(); 

            :
}

Annotation initialisation via Test Runner

Finally, you can use the custom Mockito test runner which also initialised the annotations framework:

import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;


@RunWith(MockitoJUnitRunner.class)
public class MyTest {

            :

}

Setting up your test fixture

Make sure when you create your tests that you set the mock(s) on the class being tested, the so-called System Under Test.

You can do this:

  • programmatically
  • by annotation

Setting mocks on your test class programmatically

To do this, just set the references up in the @Before-annotated setup method which sets up the test fixture (since it’s executed before each test):

import org.mockito.Mockito;


public class MyTest {

    private MyService mockService;    // mock
    private MyController controller;  // system under test; the real controller

    @Before
    public void setUp() {
         Mockito.initMocks(this);
         controller = new MyController();

         // create and set mock(s)           
         this.mockService = Mockito.mock(MyService.class);

        // set mock(s) on the system under test
         controller.setService(this.mockService);
    }

                :

}

You can use whichever means is appropriate to set the mocks on the system under test class:

In our example this might be:

  • pass the mock service in the constructor call when creating the controller
  • set the member variable on the controller directly to the mock service
  • set the mock service via a setter call which sets that member variable on the controller

Note that you might have to make the member variable(s) or setter(s) for the mock(s) at least package-private (a.k.a. “default access”) for this to work.

Setting mocks on your test class by annotation

To do this, use the @InjectMocks annotation:

import org.mockito.Mock;
import org.mockito.InjectMocks;


public class MyTest {

  @Mock
  private MyService mockService;  // mock to inject

  @InjectMocks
  private MyController controller;  // system under test; the real controller

            :

}

Note that you need to make sure that you at least have setters on the controller for this to work.

💥 Want more? Go get the FULL COURSE here: 👉 JUnit and Mockito Unit Testing for Java Developers 💥

►► Grab our FREE beginners guide to Java if you’re completely new to Java!

👉 Check out our courses at https://courses.javaeasily.com/courses
👉 Listen to our podcast at https://spotifyanchor-web.app.link/e/xjAOXisFABb
👉 Visit out our website at https://javaeasily.com/
👉 Read our articles on Medium at https://medium.com/java-easily

You can also join in the conversation by connecting with us at our Facebook page or alternatively follow us on Twitter!