Mockito 2 Tutorial – JUnit Mockito Example

In this mockito tutorial, learn the fundamentals of mockito framework, how to write junit tests along with mockito, mockito setup and annotations with example.

Table of Contents

1. Introduction
2. Setting Up
3. Annotations
4. Example

1. Mockito Introduction

During unit testing of the application, sometimes it is not possible to replicate exact production environment. Sometimes database is not available and sometimes network access is not allowed. There can be many more such restrictions. To deal with such limitations, we have to create mock for these unavailable resources.

Mockito is an open source framework that allows you to easily create test doubles (mocks). Test Double is a generic term for any case where you replace a production object for testing purposes.

In mockito, we generally work with following kind of test doubles.

  • Stubs – is an object that has predefined return values to method executions made during the test.
  • Spies – are objects that are similar to stubs, but they additionally record how they were executed.
  • Mocks – are objects that have return values to method executions made during the test and has recorded expectations of these executions. Mocks can throw an exception if they receive a call they don’t expect and are checked during verification to ensure they got all the calls they were expecting.

We can mock both interfaces and classes in the test class. Mockito also helps to produce minimum boilerplate code while using mockito annotations.

2. Mockito Setup

To add mockito into the project, we can add the desired mockito version by any means i.e. maven, gradle or jar file.

testCompile group: 'org.mockito', name: 'mockito-core', version: '2.23.4'

The complete pom file having all dependencies to create Junit tests along with mockito is given below. Otherwise, we need to find and add matching versions of objenesis, hamcrest-core, byte-buddy, byte-buddy-agent, junit and mockito.

<project xmlns=""

3. Mockito Annotations

Before hitting the keyboard to write application and unit tests, let’s quickly overview the useful mockito annotations.

  • @Mock is used for mock creation. It makes the test class more readable.
  • @Spy is used to create a spy instance. We can use it instead spy(Object) method.
  • @InjectMocks is used to instantiate the tested object automatically and inject all the @Mock or @Spy annotated field dependencies into it (if applicable).
  • @Captor is used to create an argument captor

Read More : Difference between @Mock and @InitMocks annotations

To process all above annotations, MockitoAnnotations.initMocks(testClass); must be used mat least once. To process annotations, we can use the built-in runner MockitoJUnitRunner or rule MockitoRule. We can also explicitly invoke initMocks() method in @Before annotated Junit method.


public class ApplicationTest {


public class ApplicationTest {
	@Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);



public class ApplicationTest {
	public void init() {

4. JUnit Mockito Example

Let’s learn to write junit tests which uses mocks for dependencies. The given example has a RecordService which stores a given file in database and a network location with help of DatabaseDAO and NetworkDAO.

In test environment, it is not possible to to access database or network location so we are creating mocks for both repositories.

public class DatabaseDAO 
	public void save(String fileName) {
		System.out.println("Saved in database");
public class NetworkDAO 
	public void save(String fileName) {
		System.out.println("Saved in network location");
public class RecordService 
	DatabaseDAO database;
	NetworkDAO network;
	//setters and getters

	public boolean save(String fileName) 
		System.out.println("Saved in database in Main class");;
		System.out.println("Saved in network in Main class");
		return true;

Please keep in mind if we are using any DI framework such as Spring, then we might have used the annotation @Autowired.

To test this RecordService class, let’s create a unit test.

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import com.howtodoinjava.demo.mockito.DatabaseDAO;
import com.howtodoinjava.demo.mockito.NetworkDAO;
import com.howtodoinjava.demo.mockito.RecordService;

public class ApplicationTest 
	RecordService recordService;
	DatabaseDAO databaseMock;
	NetworkDAO networkMock;
	public void saveTest()
		boolean saved ="temp.txt");
		assertEquals(true, saved);
		verify(databaseMock, times(1)).save("temp.txt");
		verify(networkMock, times(1)).save("temp.txt");

Let’s understand above test class step by step:

  • Annotate the test with the @RunWith(MockitoJUnitRunner.class) so that mockito can process the annotations.
  • Annotate the dao fields with the @Mock annotation to have a mock object instantiated for both of them.
  • Annotate service field with the @InjectMocks annotation to first instantiate and then inject both mocked dependencies.
  • Call the method to test on the class to be tested ie. recordService.
  • Verify that methods in the mocked objects have been invoked.

There are lots of other ways to test methods and mocked dependencies which we will cover in coming posts.

Drop me your questions related to this junit mockito 2 example.

Happy Learning !!

Reference : Mockito Core Java Docs

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.