The Wayback Machine - https://web.archive.org/web/20240927194435/https://www.geeksforgeeks.org/unit-testing-in-spring-boot-project-using-mockito-and-junit/
Open In App

Unit Testing in Spring Boot Project using Mockito and Junit

Last Updated : 08 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

For developers looking to enhance their skills in using Spring Boot to its full potential, enrolling in a specialized Java Backend Development course could be highly beneficial. This course will dive deeper into advanced features and best practices, offering hands-on experience to ensure you can leverage Spring Boot for efficient and effective software development.

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.

Project Flow

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)

Packages and Classes


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.



Previous Article
Next Article

Similar Reads

How to Write Test Cases in Java Application using Mockito and Junit?
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 componen
4 min read
Spring Boot – Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code. In this article, we will guide you through setting up a Spring Boot project using Gradle, a wid
4 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
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
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Migrate Application From Spring Boot 2 to Spring Boot 3
With the release of Spring Boot 3, significant changes and improvements have been introduced, particularly around Jakarta EE compliance, Java 17 support, and GraalVM native images. If you are using Spring Boot 2 and are considering migrating to Spring Boot 3, this article will walk you through the necessary steps, considerations, and potential pitf
5 min read
Spring Boot - Customizing Spring Boot Starter
Spring Boot Starters are specialized project types designed to encapsulate and distribute common functionality, simplifying the setup of Spring Boot applications. Official starters, like spring-boot-starter-web and spring-boot-starter-data-jpa, bundle dependencies, configurations, and pre-built beans for specific use cases. Creating a custom Spring
6 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
Override default Spring Boot properties in Junit Test
The Spring Boot framework provides a lot of features for testing our applications. Here, we have a tool called JUnit, which is used to test software applications. We can override default Spring Boot properties in JUnit tests, allowing us to customize the behavior of the Spring Boot Application for specific test cases. This is useful when we want to
5 min read
Unit Testing, Integration Testing, Priority Testing using TestNG in Java
TestNG is an automated testing framework. In this tutorial, let us explore more about how it can be used in a software lifecycle. Unit Testing Instead of testing the whole program, testing the code at the class level, method level, etc., is called Unit Testing The code has to be split into separate classes and methods so that testing can be carried
6 min read
Difference Between junit-vintage-engine and junit-jupiter-engine
JUnit 5 introduced a modular architecture for testing in Java, allowing developers to run tests from multiple versions of JUnit and adopt new testing paradigms. Two of the key components of JUnit are the junit-vintage-engine and the junit-jupiter-engine. Each serves a different purpose, one focuses on backward compatibility with older tests (JUnit
6 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
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
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Migrating a Spring Boot Application from Spring Security 5 to Spring Security 6
Spring Security is a powerful authentication and access control framework for Java applications specially for those built with the Spring Framework. With the release of Spring Security 6, several enhancements and changes have been introduced to simplify the security configuration and provide better performance and security features. This article ai
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
JUnit 5 vs JUnit 4
JUnit 4 and JUnit 5 both are Java-based testing frameworks, The JUnit 5 is the advanced testing framework when compared with JUnit 4. The JUnit provides a lot of features like Annotation-based coding, parallel test execution, and other features. Difference between JUnit 5 and JUnit 4Topic JUnit 5 JUnit 4 Architecture JUnit 5 supports designs with m
4 min read
Spring Boot MockMVC Testing with Example Project
In a Spring Boot project, we have to test the web layer. For that, we can use MockMVC. In this tutorial, let us see how to do that by having a sample GeekEmployee bean and writing the business logic as well as the test cases for it. Example Project Project Structure: This is a maven project. Let's start with pom.xml C/C++ Code <?xml version=
5 min read
Maven Project - HashMap and HashSet Collections with JUnit Testing
In many software, we will be working with HashMap and HashSet and always there is confusion exists that when to use HashMap and when to use HashSet. As a sample project, a use case containing the "GeekAuthor" class is taken and it has different attributes namely authorNameauthorIdareaOfInterestpublishedArticles Let us try to add the "GeekAuthor" da
7 min read
Maven Project - Phone Number Validations and Testing via JUnit
Any web/mobile/console application should be error-free and hence it has to undergo a lot of validations. In this article, let us see how to validate phone numbers with and without country codes and test the same via JUNIT to check whether the given testing phone numbers are correct or not. Via a maven project, let us do the same. Example Project P
4 min read
Maven Project - LinkedHashMap and LinkedHashSet usage Along with JUnit Testing
In software programming, there are many instances where we need the usage of LinkedHashMap and LinkedHashSet. LinkedHashSet Though HashSet is available, if we need the ordered version of HashSet, we need the LinkedHashSet. The advantage is when we iterate the LinkedHashSet, we get the display of the elements in the inserted order. Because of the ex
7 min read
Testing Spring Security Auth with JUnit
Here we are going to learn how to use InMemoryDaoImpl to verify Spring security authentication using a JUnit test case and how to programmatically create a fully complete authentication object and then utilize it in an application. SecurityContextHolder: Spring security is built on the concept of a security context, which is somewhat static. This s
4 min read
JUnit Testing For MySQL Project in Java
For testing a software project, automated testing is always good and that will produce error-prone results. In the case of manual testing, there are possibilities of human errors. In this article let us take a sample project and let us see how to write JUnit test cases for it. Example Project Project Structure: As this is the Maven-driven project,
6 min read
JUnit - Inventory Stock Testing as a Maven Project
The quality of the software is very important. Though Unit tests and integration tests are done in the manual testing way, we cannot expect all kinds of scenarios to test. Hence as a testing mechanism, we can test a software code or project by means of JUnit. In this article let us see how to do testing for inventory stock by using JUnit. Via a Mav
4 min read
Test Driven Development using JUnit5 and Mockito
Test Driven Development is the process in which test cases are written before the code that validates those cases. It depends on the repetition of a very short development cycle. Test Driven Development is a technique in which automated Unit tests are used to drive the design and free decoupling of dependencies. In this article via a sample project
8 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 Java provides a way to store the ordered collecti
5 min read
Difference Between @Mock and @InjectMocks in 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. Unit Testing is a type of software testing in which individual software
3 min read
WireMock vs Mockito
WireMock and Mockito both are testing tools and both tools are highly used in real-world applications for Unit and Integration testing. And the developer must know the difference between these two testing tools. So in this article, we are going to discuss the main differences between these two very popular testing tools. WireMock WireMock is a tool
3 min read
Generate Model Classes using jsonSchema2Pojo (website and Maven Dependency) For a Spring Boot Project That Consumes API
Generating Java model classes from a JSON schema is a common task when building applications that consume APIs, especially in Spring Boot projects. It simplifies the development process by mapping POJOs (Plain Old Java Objects) directly to the API's JSON structure. In this article, we explore how to use jsonSchema2Pojo, both as a web tool and as a
4 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Practice Tags :