Mockito

Mockito Test Case Example

Photo of Mohammad Meraj ZiaMohammad Meraj ZiaAugust 3rd, 2016Last Updated: April 9th, 2019
0 558 4 minutes read

A unit test should test a class in isolation. Side effects from other classes or the system should be eliminated if possible. Mockito lets you write beautiful tests with a clean & simple API. In this example we will learn how to write a simple test case using Mockito. Tools and technologies used in this example are Java 1.8, Eclipse Luna 4.4.2

1. Introduction

Mockito is a popular mocking framework which can be used in conjunction with JUnit. Mockito allows us to create and configure mock objects. Using Mockito simplifies the development of tests for classes with external dependencies significantly. We can create the mock objects manually or we can use the mocking framewors like Mockito, EasyMock. jMock etc. Mock frameworks allow us to create mock objects at runtime and define their behavior. The classical example for a mock object is a data provider. In production, a real database is used, but for testing a mock object simulates the database and ensures that the test conditions are always the same.

2. Creating a project

Below are the steps required to create the project.

  • Open Eclipse. Go to File=>New=>Java Project. In the ‘Project name’ enter ‘MockitoExample’.

Figure 1. Create Java Project
Figure 1. Create Java Project

  • Eclipse will create a ‘src’ folder. Right click on the ‘src’ folder and choose New=>Package. In the ‘Name’ text-box enter ‘com.javacodegeeks’. Click ‘Finish’.

Figure 2. Java Project
Figure 2. Java Project

  • Right click on the package and choose New=>Class. Give the class name and click ‘Finish’. Eclipse will create a default class with the given name.

3.1 Declaring mockito dependency

For this example we need the junit and mockito jars. These jars can be downloaded fromMaven repository. We are using ‘junit-4.12.jar’ and ‘mockito-all-1.10.19.jar’. There are the latests versions available as per now. To add these jars in the classpath right click on the project and choose Build Path=>Configure Build Path. The click on the ‘Add External JARs’ button on the right hand side. Then go to the location where you have downloaded these jars. Then click ok.

If you are using Gradle you can do:

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

4. Code

In this section we will see some simple code examples.

4.1 Mock

To mock the class we make use of themock() method of theMockito class. It creates a mock object of a given class or interface:

public static <T> T mock(Class<T> classToMock)

Below is the code snippet we use to mock:

// Create MockStack<String> mockStack = Mockito.mock(Stack.class);

Mockito also supports the creation of mock objects based on the@Mock annotation. You annotate the class with@Mock as below:

@Mock private IReportGenerator reportGenerator;

Then you annotate the class (which you want to test) which has the reference to this mocked class with @InjectMocks:

@InjectMocks private ReportGeneratorService reportGeneratorService;

After this you need to initialize the mocks. We can do this by calling the initMocks() method of MockitoAnnotations class.

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

4.2 Verify

Let us see the usage ofverify() method of Mockito class. This verifies that certain behavior happened once. You can also use another overloaded method which takes an extra integer argument (times(int)). The arguments passed are compared usingequals() method. Let’s see an example now.

// Create MockStack<String> mockStack = Mockito.mock(Stack.class);// Use mock objectmockStack.add("Test verify");Mockito.verify(mockStack).add("Test verify");

4.3 Stub

In this section we will see how we can stub a method call. To stub a method we will make use of thewhen() method. Stubbing can be overridden: For example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing. Once stubbed, the method will always return stubbed value regardless of how many times it is called. Last stubbing is more important – when you stubbed the same method with the same arguments many times. Although it is possible to verify a stubbed invocation, usually it’s just redundant.

Want to master Mockito ?
Subscribe to our newsletter and download theMockitoProgramming Cookbookright now!
In order to get you prepared for your Mockito development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

The other method we use for stubbing isthenReturn(). It sets a return value to be returned when the method is called. See the code snippet below:

// Create MockStack<String> mockStack = Mockito.mock(Stack.class);Assert.assertEquals(mockStack.capacity(), 0);// StubMockito.when(mockStack.capacity()).thenReturn(10);Assert.assertEquals(mockStack.capacity(), 10);Mockito.verify(mockStack);

4.4 Argument matchers

Mockito verifies argument values in natural java style: by using anequals() method. Sometimes, when extra flexibility is required then you might use argument matchers:

Stack<String> mockStack = Mockito.mock(Stack.class);Mockito.when(mockStack.get(Mockito.anyInt())).thenReturn("PASS");Assert.assertEquals(mockStack.get(0), "PASS");Assert.assertEquals(mockStack.get(10), "PASS");Mockito.verify(mockStack, Mockito.times(2)).get(Mockito.anyInt());

Argument matchers allow flexible verification or stubbing. Be reasonable with using complicated argument matching. The natural matching style usingequals() with occasionalanyX() matchers tend to give clean & simple tests. Sometimes it’s just better to refactor the code to allowequals() matching or even implementequals() method to help out with testing. If you are using argument matchers, all arguments have to be provided by matchers.

4.5 Stub void method

In this section we will see how we can stub void methods with exception. We will make use of thedoThrow() method of the Mockito class

mock = Mockito.mock(VoidMethodClass.class);Mockito.doThrow(new IllegalArgumentException()).when(mock).voidMethodThrowingExcetion(false);mock.voidMethodThrowingExcetion(true);Mockito.doThrow(new IllegalArgumentException()).when(mock).voidMethodThrowingExcetion(true);try {  mock.voidMethodThrowingExcetion(true);  Assert.fail();} catch (IllegalArgumentException e) {}

5. Download the source file

This was a very simple example of using Mockito to write unit tests. There are lots of other features which Mockito provides. You can look at the Mockito website for more details.

Download
You can download the full source code of this example here:MockitoExample
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Mohammad Meraj ZiaMohammad Meraj ZiaAugust 3rd, 2016Last Updated: April 9th, 2019
0 558 4 minutes read
Photo of Mohammad Meraj Zia

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.