How to Write Test Cases in Java Application using Mockito and Junit?
Last Updated :
09 Mar, 2023
Mockito is an open-source testing framework used for unit testing of Java applications. It plays a vital role in developing testable applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in Unit Testing. Unit Testing is a type of software testing in which individual components of the software are tested. The major objective of using the Mockito framework is to simplify the development of a test by mocking external dependencies and using them in the test code. And as a result, Mockito provides a simpler test code that is easier to understand, more readable, and modifiable. Mockito can also be used with other testing frameworks like JUnit and TestNG.
JUnit framework is a Java framework that is also used for testing. Now, JUnit is used as a standard when there is a need to perform testing in Java. So in this article, we will be discussing test cases in a java application using Mockito and Junit.
Step by Step Implementation
Step 1: Create a Maven project in your favorite Java IDE (IHere we are using IntelliJ IDEA)

Step 2: When you have successfully created a maven project you have to add some dependencies in your pom.xml file. We have to add the following dependency in your pom.xml file.
Dependency for Mockito is as follows:
XML
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
Dependency for Junit is as follows:
XML
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
Implementation: Below is the complete code for the pom.xml file
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mockito-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
Step 3: Now you have to create one interface named as TodoService and one class named as TodoServiceImpl.
Java
// Java Program to Illustrate TodoService File
// Importing List class
import java.util.List;
// Interface
public interface TodoService {
// Creating a simple method retrieveTodos()
public List<String> retrieveTodos(String user);
}
Java
// Java Program to Illustrate TodoServiceImpl File
// Importing required classes
import java.util.ArrayList;
import java.util.List;
// Main class
public class TodoServiceImpl {
// Creating a reference of
// TodoService interface
private TodoService todoService;
// Constructor
public TodoServiceImpl(TodoService todoService)
{
// This keyword refers to same instance itself
this.todoService = todoService;
}
// Method
// Filtering the string
public List<String>
retrieveTodosRelatedToJava(String user)
{
List<String> filteredTodos
= new ArrayList<String>();
List<String> todos
= todoService.retrieveTodos(user);
for (String todo : todos) {
// Filtering the string that contains "Java"
// keyword
if (todo.contains("Java")) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
}
Step 4: Now we are going to perform unit testing for the retrieveTodosRelatedToJava() method that is present inside the TodoServiceImpl.java file. To create the test class follow these steps. At first Right-click inside the TodoServiceImpl.java file.
Then click on the Generate button.

Then click on the Test button.

A pop-up window will be shown like this. Here you can modify your test class name. Also, check the setUp and the method that you want to perform unit testing.

Example:
Java
// Java Program to Illustrate TodoServiceImplMockTest File
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
// Importing required classes
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
// MockitoJUnitRunner gives automatic validation
// of framework usage, as well as an automatic initMocks()
@RunWith(MockitoJUnitRunner.class)
// Main class
public class TodoServiceImplMockTest {
TodoServiceImpl todoBusiness;
// The Mockito.mock() method allows us to
// create a mock object of a class or an interface
@Mock TodoService todoServiceMock;
// Methods annotated with the @Before
// annotation are run before each test
@Before public void setUp()
{
todoBusiness = new TodoServiceImpl(todoServiceMock);
}
// @Test
// Tells the JUnit that the public void method
// in which it is used can run as a test case
@Test
public void testRetrieveTodosRelatedToSpring_usingMock()
{
List<String> todos
= Arrays.asList("Learn Spring", "Learn Java",
"Learn Spring Boot");
when(todoServiceMock.retrieveTodos("User"))
.thenReturn(todos);
List<String> filteredTodos
= todoBusiness.retrieveTodosRelatedToJava(
"User");
assertEquals(1, filteredTodos.size());
}
@Test
public void
testRetrieveTodosRelatedToSpring_withEmptyList_usingMock()
{
List<String> todos = Arrays.asList();
when(todoServiceMock.retrieveTodos("Dummy"))
.thenReturn(todos);
List<String> filteredTodos
= todoBusiness.retrieveTodosRelatedToJava(
"Dummy");
assertEquals(0, filteredTodos.size());
}
}
Now you have successfully written two test cases for your java application. Now to run the test cases click on the green button as shown in the below image. And you can see your test cases have been passed.

Similar Reads
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means âNext Generationâ and it is influenced by JUnit and it follows the annotations (@). Â End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via
4 min read
Generate Junit Test Cases Using Randoop API in Java
Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort
4 min read
How to Test Java List Interface Methods using Mockito?
Mockito is an open-source testing framework used for unit testing of Java applications. It plays a vital role in developing testable applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in Unit Testing. The List interface in
5 min read
Encode and Decode Strings in Java with JUnit Tests
Strings are very useful and they can contain sequences of characters and there are a lot of methods associated with Strings. Moreover, encoding and decoding are possible for a given use case and it can be validated whether are they equal or not for a given requirement. They can be tested for validit
4 min read
Unit Testing in Spring Boot Project using Mockito and Junit
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
6 min read
How to Test a Maven Project using EasyMock?
Always a software project is prepared and tested as an individual unit. We pass different scenarios and expect the original values should match. One such approach is "Easymock" and in this article via a sample project, handled when and how to mock void methods. We are going to see this approach via
3 min read
How to Generate Code Coverage Report with JaCoCo in Java Application?
Testing is a most important part of a software development lifecycle. Without testing, the software is not ready for deployment. To test Java applications we mostly used Junit. JUnit framework is a Java framework that is used for testing. And now, JUnit is used as a standard when there is a need to
4 min read
JUnit - Writing Sample Test Cases for StudentService in Java
In many parts of projects, collections play a major role. Among that ArrayList is a user-friendly collection and many times it will be required to develop software. Let us take a sample project that involves a "Student" model that contains attributes such as studentId, studentName, courseName, and G
5 min read
Testing an Android Application with Example
Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
5 min read
JUnit Test Execution For a MongoDB Collection using Maven
MongoDB is a NoSQL versatile database and it is widely used in software industries. Wherever there is no strict relational database relationship is necessary and also if there are chances of fetching the document often, it is always good to go with MongoDB. In this article, let us see the ways of C
4 min read