Mockito
Mockito is one of the popular testing frameworks for Java applications. This provides a way to test the functionality of the isolated classes without requiring dependencies like filesystem read/write operations, database connection, or other external services. Mockito API is a clean and intuitive API. Mockito facilitates the creation of mock objects seamlessly. Mockito uses Java Reflection to create mock objects for a given interface. Mock objects are just a proxy for actual implementations. We will present how to start using Mockito in Java projects.
Features of Mockito
Apart from basic tasks of a mocking framework like the creation of test doubles, stubbing, setting expectations, and verification of behavior, Mockito has some features which distinguish it from other mocking frameworks:
- Exception Support - support for exceptions.
- Annotations - mock objects can be created using annotations.
- Return value support - support for the return values.
- No Handwriting - mock objects don’t need to be manually written.
- Refactoring Safe - Renaming the interface method names or reordering the parameters will not break the test code as the Mocks are created at runtime.
- Order check support − Supports check on the order of method calls.
Mockito Setup
For the Mockito Setup, you just need to do the following. This will add Mockito's main JAR file with all the required dependencies.
Maven: Add the following to the pom.xml file:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.5.9</version>
<scope>test</scope>
</dependency>
Gradle :
compile group: 'org.mockito', name: 'mockito-core', version: '3.5.9'
Ivy :
<dependency org="org.mockito" name="mockito-core" rev="3.5.9"/>
Mockito Annotations
Mockito framework consists of several annotations, which are replacements for the usual methods available in the API and makes the test code clean and easy to understand.
The Mockito annotations are as follows:
- @Mock - This is used to create a mocked instance. Objects annotated with @Mock can be used anywhere in the test,
- @InjectMocks- This is used to inject mock instances into the tested object,
- @Spy- This is used to create a proxy for a provided instance. Here we can decide which method of spied object will be stubbed,
- @Captor - This is used to create an argument captor.
To activate the Mockito annotations in test classes, we need to use one of the following three solutions
// 1.)
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
// test cases
}
// 2.)
//In JUnit 4:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);|
}
//In Junit 5 :
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}

You can also try this code with Online Java Compiler
Run Code
// 3.)
public class TestClass {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
// test cases
}

You can also try this code with Online Java Compiler
Run Code
Mockito Example
Let’s create a mock of Equity Service to get the dummy prices of some equity and unit test a Java class named Portfolio.
Please note the following for a better understanding of the test case :
- Portfolio − It is an object to carry a list of entities and to get the market value computed using entity prices and entity quantity.
- Entity − An object to carry the details of an entity such as its id, name, quantity, etc.
- EntityService − A entity service returns the current price of an entity.
- mock(...) − Mockito created a mock entity service.
- when(...).thenReturn(...) − Mock implementation of getPrice method of EntityService interface. For googleEntity, return 50.00 as the price.
- portfolio.setEntity(...) − The portfolio now contains a list of two entities.
- portfolio.setEntityService(...) − Assigns the EntityService Mock object to the portfolio.
-
portfolio.getMarketValue() − This returns the market value based on its entity using the mock entity service.
A step-by-step discussion is given below :
Step 1 − Create a JAVA class to represent the Equity.
File: Equity.java
package mockitoTesting;
public class Equity {
private String equityId;
private String name;
private int quantity;
public Equity(String equityId, String name, int quantity){
this.equityId = equityId;
this.name = name;
this.quantity = quantity;
}
public String getEquityId() {
return equityId;
}
public void setEquityId(String equityId) {
this.equityId = equityId;
}
public int getQuantity() {
return quantity;
}
public String getName() {
return name;
}
}

You can also try this code with Online Java Compiler
Run Code
Step 2 − Create an interface EquityService to get the price of an equity.
File: EquityService.java
package mockitoTesting;
public interface EquityService {
public double getPrice(Equity equity);
}

You can also try this code with Online Java Compiler
Run Code
Step 3 − Create a class Portfolio to represent the portfolio of any client.
File: Portfolio.java
package mockitoTesting;
import java.util.List;
public class Portfolio {
private EquityService equityService;
private List<Equity> equity;
public EquityService getEquityService() {
return equityService;
}
public void setEquityService(EquityService equityService) {
this.equityService = equityService;
}
public List<Equity> getEquity() {
return equity;
}
public void setEquity(List<Equity> equity) {
this.equity = equity;
}
public double getMarketValue(){
double marketValue = 0.0;
for(Equity equity:equity){
marketValue += equityService.getPrice(equity) * equity.getQuantity();
}
return marketValue;
}
}

You can also try this code with Online Java Compiler
Run Code
Step 4 − Test Portfolio class
Let's test the Portfolio class, by injecting a mock of equityservice into it. Mock will be created by Mockito.
File: PortfolioTester.java
package tests;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import mockitoTesting.Portfolio;
import mockitoTesting.Equity;
import mockitoTesting.EquityService;
import static org.mockito.Mockito.*;
public class PortfolioTester {
Portfolio portfolio;
EquityService equityService;
public static void main(String[] args){
PortfolioTester tester = new PortfolioTester();
tester.setUp();
System.out.println(tester.testMarketValue()?"passed the mockito test":"failed the mockito test");
}
public void setUp(){
//Create a portfolio object for testing
portfolio = new Portfolio();
//Create a mock object of the equity service
equityService = mock(EquityService.class);
//set the equityService to the portfolio
portfolio.setEquityService(equityService);
}
public boolean testMarketValue(){
//Creates a list of equities to be added to the portfolio
List<Equity> equity = new ArrayList<Equity>();
Equity googleEquities = new Equity("1","Google", 10);
Equity microsoftEquities = new Equity("2","Microsoft",100);
equity.add(googleEquities);
equity.add(microsoftEquities);
//add equity to the portfolio
portfolio.setEquity(equity);
//mock the behavior of equity service to return the value of various equity
when(equityService.getPrice(googleEquities)).thenReturn(50.00);
when(equityService.getPrice(microsoftEquities)).thenReturn(1000.00);
double marketValue = portfolio.getMarketValue();
return marketValue == 100500.0;
}
}

You can also try this code with Online Java Compiler
Run Code
Step 5 − Verify the result.
Compile the classes and run the PortfolioTester.
Output :

Frequently Asked Questions
-
What are the limitations of mockito?
Following are some limitations of Mockito :
a) It cannot mock constructors, private methods, static methods, and final classes.
b) It requires Java version 6 plus to run.
c) It also cannot mock equals(), hashCode() methods.
-
Can we Mock private methods using Mockito?
Mockito does not support mocking private and static methods. To test private methods, we need to refactor the code to change the access to protected (or package) and we have to avoid the static/final methods.
-
Can we do the mocking of the void method using Mockito?
By using the doNothing() method we can completely ignore the void method call.
-
What is the difference between Mockito and JUnit?
Mockito is a library that enables the writing of tests using the mocking approach. In comparison, JUnit is the Java library used to write and run the tests.
Conclusion
In this blog, we started with the Mockito introduction. Then we discussed the Mocking and features of Mockito. We have also seen different annotations in the Mockito framework. In order to start with an example of Mockito first, we discussed the installation and setup of the Mockito, and then we had a step-by-step discussion of the test case using Mockito.
We hope that this blog helped you enhance your knowledge in getting started with Mockito. If you would also like to learn about JUnit testing then please visit.
Learning never stops, and to learn more and become more skilled, head over to our practice platform Coding Ninjas Studio, to practice top problems attempt Mock Tests, read informative blogs, and interview experiences. Do upvote our blog to help other ninjas grow.
Happy Learning!