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
<? 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     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.
Â
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> {     @Query (         "SELECT CASE WHEN COUNT(s) > 0 THEN TRUE ELSE FALSE END FROM Person s WHERE s.personId = ?1" )     Boolean     isPersonExitsById(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 { Â
    @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.
Â
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; Â
@RestController public class PersonController { Â
    @Autowired     private PersonService personService; Â
    @GetMapping ( "/persons" )     public ResponseEntity<?> getAllPersons() {         return ResponseEntity.ok( this .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 create one class named as PersonRepoTest.Â
Â
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     private Integer personId;     private String personName;     private String personCity; } |
Â
Â
Step 11: Unit Testing of Service Class
Â
Inside the test > services package create one class named as PersonServiceTest.Â
Â
Java
// Java Program to Illustrate Unit Testing of Service Class Â
package com.demo.services; Â
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; Â
@ExtendWith (MockitoExtension. class ) Â
// Main class class PersonServiceTest { Â
    @Mock private PersonRepo personRepo; Â
    private PersonService personService; Â
    @BeforeEach void setUp()     {         this .personService             = new PersonService( this .personRepo);     } Â
    @Test void getAllPerson()     {         personService.getAllPerson();         verify(personRepo).findAll();     } } |
Â
Â
Similarly, we can perform testing of different units of your spring boot project.Â
Â