Mockito Setup
Integrating Mockito into Java projects is easy. The mockito library is available under the Maven Central Repository. So, we just need to add a dependency to our project dependency manager:
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"/>
This will add Mockito's main JAR file with all the required dependencies.
To use Mockito with JUnit 5, we need to include an additional dependency: mockito-junit-jupiter. At the same time, mockito works well without different libraries with JUnit in version 4.
Import
Most of the Mockito facilities are static methods of org.mockito.Mockito. Thus, Mockito can be statically imported into a class in this way:
import static org.mockito.Mockito.*;
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.
In order to activate the Mockito annotations in test classes, we need to use one of the following three solutions:
-
Annotating the JUnit test class with a MockitoJUnitRunner:
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
// test cases
}

You can also try this code with Online Java Compiler
Run Code
-
Explicitly invoking MockitoAnnotations.initMocks() in the method which will be called before each test:
In JUnit 4:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);|
}

You can also try this code with Online Java Compiler
Run Code
In JUnit 5:
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}

You can also try this code with Online Java Compiler
Run Code
-
In JUnit from version 4.7 onwards, we can use a dedicated rule which will initialize the mocks annotated with @Mock before each test method - MockitoJUnit.rule():
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.
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
-
Can we mock static methods?
Since the static method belongs to the class, there is no way in Mockito to mock static methods. However, PowerMock, along with the Mockito framework, can be used to mock static methods.
-
How is mock different from stub?
A Mock is just testing behavior, making sure specific methods are called. Whereas, a Stub is a testable version of a particular object.
-
What is mockito-inline?
Versions 2.7.6 onwards, there is a ‘'mockito-inline' artifact which enables inline mock making without configuring the MockMaker extension file.
-
Can we mock an interface?
The mock() method in Mockito allows us to create a mock object of a class or an interface.
Conclusion
In this blog, we started with the Mockito introduction. Then we discussed the installation and setup of the Mockito. We have also seen different annotations in the Mockito framework. In the end, we had a step-by-step discussion on how to use Mockito in a java project.
We hope that this blog helped you enhance your knowledge in getting started with Mockito. 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!