Skip to content
Related Articles

Related Articles

Unit Testing in Spring Boot Project using Mockito and Junit

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 24 Feb, 2022

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 avoiding heavy configuration of XML which is present in spring
  • It provides easy maintenance and creation of REST endpoints
  • It includes embedded Tomcat-server
  • Deployment is very easy, 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 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 are going to perform Unit Testing in Spring Boot Project using Mockito and Junit.

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 version="1.0" encoding="UTF-8"?>
        <relativePath/> <!-- lookup parent from repository -->



Step 3: Create the packages and files as seen in the below image. Below is the complete file structure fo this project.



  • 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 file.



package com.demo.entites;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
// Class
public class Person {
    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.



package com.demo.repo;
import com.demo.entites.Person;
// Interface
// Extends JpaRepository
public interface PersonRepo
    extends JpaRepository<Person, Integer> {
        "SELECT CASE WHEN COUNT(s) > 0 THEN TRUE ELSE FALSE END FROM Person s WHERE s.personId = ?1")
    isPersonExitsById(Integer id);



Step 6: Inside the service package


Inside the package create one class named as PersonService



import com.demo.entites.Person;
import com.demo.repo.PersonRepo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Annotation
// Class
public class PersonService {
    @Autowired private PersonRepo repo;
    public List<Person> getAllPerson()
        return this.repo.findAll();
    public PersonService(PersonRepo repo)
        // this keyword refers to current instance
        this.repo = repo;



Step 7: Inside the controller package


Inside the package create one class named as PersonController.



package com.demo.controllers;
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;
public class PersonController {
    private PersonService personService;
    public ResponseEntity<?> getAllPersons() {
        return ResponseEntity.ok(this.personService.getAllPerson());



Step 8: Below is the code for the file



# Configuration for MySQL Database


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 create one class named as PersonRepoTest



package com.demo.repo;
import com.demo.entites.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class PersonRepoTest {
    private PersonRepo personRepo;
    void isPersonExitsById() {
        Person person = new Person(1001, "Amiya", "Bhubaneswar");;
        Boolean actualResult = personRepo.isPersonExitsById(1001);



Step 11: Unit Testing of Service Class


Inside the test > services package create one class named as PersonServiceTest



// Java Program to Illustrate Unit Testing of Service Class
import static org.mockito.Mockito.verify;
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;
// Main class
class PersonServiceTest {
    @Mock private PersonRepo personRepo;
    private PersonService personService;
    @BeforeEach void setUp()
            = new PersonService(this.personRepo);
    @Test void getAllPerson()



Similarly, we can perform testing of different units of your spring boot project. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!