Unit Testing in Spring Boot Project using Mockito and Junit
Last Updated :
02 Jan, 2025
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 setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:
- It allows for avoiding heavy configuration of XML which is present in spring.
- It provides easy maintenance and creation of REST endpoints.
- It includes an embedded Tomcat server.
- Deployment is straightforward, war and jar files can be easily deployed in the Tomcat server.
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 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. 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 are going to perform Unit Testing in Spring Boot Project using Mockito and JUnit.
Annotations:
- @Mock: This annotation is used when we have to create and inject mock objects. It is used in testing frameworks like Mockito. Whenever a real object is to be stimulated, a mock object is used because it does so in a controlled manner.
- Creation: Mockito creates a mock instance while @Mock is used.
- Injection : @InjectMocks is used to automatically inject mocked dependencies to the object that is being tested.
- @Inject: This annotation is used to inject dependencies into a class. It belongs to Java Dependency Injection framework, it is used to make the code modular and testable by decoupling creation which means instead of creating its own dependencies, a class receives them from outside, making the class simpler.
- assert Method: It is used to check whether a condition is true. If condition is false, the test is failed and error is generated. It a part of testing to confirm that the code is behaving as expected. It is used for equality check, boolean check, null check, exception check, etc.
Step-by-Step Implementation
Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project.
Step 2: Add the following dependency as listed below as follows:
- Spring Web
- MySQL Database
- Lombok
- Spring Data JPA
Example: 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>BootDemoApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BootDemoApp</name>
<description>BootDemoApp</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 3 : Create the packages and files as seen in the below image. Below is the complete file structure of this project.

Note :
- Green Rounded Icon ‘I’ Buttons are Interface.
- Blue Rounded Icon ‘C’ Buttons are Classes.
Step 4: Inside the entity package
It is done via creating a simple POJO class inside the Person.java file.
Java
package com.demo.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
// Class
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer personId;
private String personName;
private String personCity;
}
Step 5: Inside the repository package
Create a simple interface and name the interface as PersonRepo. This interface is going to extend the JpaRepository.
JpaRepository: It takes two generic Parameters. First of entity and other of Type of Primary Key. Here entity is Person and Integer is Primary Key.
Java
package com.demo.repo;
import com.demo.entities.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
// Interface
// Extends JpaRepository
public interface PersonRepo
extends JpaRepository<Person, Integer> {
//Spring data jpa will automatically provide implementation for it when using existsBy{fieldName}
Boolean existsById(Integer id);
}
Step 6: Inside the service package
Inside the package create one class named as PersonService .
Java
package com.demo.services;
import com.demo.entities.Person;
import com.demo.repo.PersonRepo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
public class PersonService {
//No need to use @Autowired when using Constructor Injection
//Dependencies are final
private final PersonRepo repo;
public PersonService(PersonRepo repo)
{
// this keyword refers to current instance
this.repo = repo;
}
public List<Person> getAllPerson()
{
return repo.findAll();
}
}
Step 7: Inside the controller package
Inside the package create one class named as PersonController.
Java
package com.demo.controllers;
import com.demo.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.demo.entity.Person
@RestController
public class PersonController {
//Constructor Based Injection No need of using @Autowired
private final PersonService personService;
public PersonController(PersonService personService){
this.personService=personService;
}
@GetMapping("/persons")
public ResponseEntity<List<Person>> getAllPersons() {
return ResponseEntity.ok(personService.getAllPerson());
}
}
Step 8: Below is the code for the application.properties file
server.port=8082
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/schooldb
spring.datasource.username=amiya559
spring.datasource.password=password.123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
Now your sample spring boot project is ready, and we are going to perform unit testing in this sample project.
Step 9: Create the following packages and the classes as shown in the below image. (Inside the green color box)

Step 10: Unit Testing of Repository Class
Inside the test > repo package creates one class named as PersonRepoTest .
Java
package com.demo.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Builder;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
// Class
public class Person {
@Id
private Integer personId;
private String personName;
private String personCity;
}
Step 11: Unit Testing of Service Class
Inside the test > services package creates one class named as PersonServiceTest .
Java
// Java Program to Illustrate Unit Testing of Service Class
package com.demo.services;
//USing BDD Mockito
import static org.mockito.BDDMockito.verify;
import static org.mockito.BDDMockito.given;
import static org.assertj.core.api.Assertions.assertThat;
import com.demo.repo.PersonRepo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
// Main class
class PersonServiceTest {
@Mock
private PersonRepo personRepo;
//When using Mockito Use @InjectMocks to inject
//Mocked beans to following class
@InjectMocks
private PersonService personService;
@Test
void getAllPerson()
{
//given
Person person= new Person( 1,"Ahnis","Gotham");
Person person2= new Person(2,"Saksham","New york");
//When
given(personRepo.findAll())
.willReturn(List.of(person,person2));
var personList = personService.getAllPerson();
//Then
//Make sure to import assertThat From org.assertj.core.api package
assertThat(personList).isNotNull();
assertThat(personList.size()).isEqualTo(2);
}
}
Similarly, we can perform testing of different units of your spring boot project.
Similar Reads
Advantages of Spring Boot JDBC
Spring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcT
3 min read
Spring Boot - Packaging
The Spring Framework was created to provide an open-source application framework to feature better infrastructure support for developing Java applications. It is one of the most popular Java Enterprise Edition (Java EE) frameworks, Spring framework helps developers in creating high-performing applic
11 min read
Spring Boot - JDBC
Spring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by
8 min read
Spring Boot - AOP After Throwing Advice
Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as
6 min read
Spring Boot - AOP After Returning Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
5 min read
Multi-Module Project With Spring Boot
Multi-Module project with Spring Boot refers to a project structure where multiple modules or subprojects are organized under a single parent project. Each module can represent a distinct component, functionality, or layer of the application, allowing for better organization, maintainability, and co
6 min read
Spring Boot - AOP After Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
5 min read
Spring Boot - AOP Before Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
4 min read
Spring Boot - DevTools
Spring Boot provides DevTools, a module designed to ease your development process, it improves the experience of developing applications resulting in optimizing the developer's productivity for building exceptional software. It aims to reduce development time, by intelligently detecting code changes
5 min read
Spring Boot - Dependency Management
Spring Boot framework is the most popular web development framework. No doubt, it provides an abundance of essential features and a convenient way to handle those features. At the heart of Spring Boot is the 'Dependency Management' feature. Importance of Dependency ManagementCentralized Dependency M
6 min read