EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot Unit Test
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot Unit Test

Spring Boot Unit Test

Introduction to Spring Boot Unit Test

Spring Boot Unit Test is testing done by developers that makes sure the individual units or component functionalities do work as expected. Writing unit test cases is considered one of the difficult parts, but the mechanism that supports unit test cases is easier. Before checking out what is Spring Boot unit test, we need to know some of the fundamentals of Testing. As a developer, unit testing and integration testing is an essential part, especially for newbies. Every Spring boot application is enclosed with Spring Initializr, which gives a strong foundation for writing unit test cases. Spring boot test will, by default, include and manage versions of Junit 4/5, Mockito Library, and Assertion libraries like Hamcrest, JsonPath libraries, etc. Let us look deeper into the Spring Boot unit test and its applications.

Unit testing is a software testing method by which individual source code units, or a set of one or more programming modules with control data, usage, and operation procedures, that are tested to determine if they fit for usage.

Creation of Spring Boot unit Test Code

Below we will see how to create Spring Boot Unit Test:

  1. Using Mockito:

To inject Mockito Mocks to Spring Beans, Mockito core dependency has to be added to the build configuration file. Below are the dependencies,

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
People using Gradle can add dependencies in build.gradle file,
compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
Consider a Service class that contains method with some functionality,
@Service
public class <Service class name> {
public <data type> <method name>() {
return ……
}
}

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

Examples of Spring Boot Unit Test Code

Step 1: Creating a Service class that contains a method to return a string value.

package com.src.sample;
import org.springframework.stereotype.Service;
@Service
public class Employee {
public String getEmpName() {
return "Karthik";
}
}

Step 2: Injecting Employee class into another class file,

package com.src.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Designation {
@Autowired
Employee emp;
public Designation(Employee emp) {
this.emp = emp;
}
public String getDesignation() {
return emp.getEmpName ();
}
}

Step 3: Main Spring boot application class,

package com.src.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MockitoSampleApp {
public static void main(String[] args) {
SpringApplication.run(MockitoSampleApp.class, args);
}
}

Step 4: Now, we need to configure the Application Context for unit tests. Annotation @Profile(“test”) is used in configuring class while Test cases are running.

package com.src.sample;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("test")
@Configuration
public class EmployeeTestConfiguration {
@Bean
@Primary
public Employee emp() {
return Mockito.mock(Employee.class);
}
}

Step 5: To write a Unit Test case for the Designation test case.

package com.src.sample;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoSampleAppTests {
@Autowired
private Designation desg;
@Autowired
private Employee emp;
@Test
public void whenEmpIdIsProvided_thenNameIsCorrect() {
Mockito.when(emp.getEmpName ()).thenReturn("Mock Employee Name");
String test1 = desg.getEmpName();
Assert.assertEquals("Mock Employee Name", test1);
}
}

Step 6: To complete with the unit testing, the POM configuration needs to be done accordingly.

Step 7: Once the POM configuration is done, use Maven commands.

Step 8: You can run Spring Application using Maven or Gradle commands.

Maven, use command,
mvn clean install
Gradle, use command,
gradle clean build

Spring Boot Unit Test output

Providing a Constructor

Dependency injection makes code less dependent on containers than on the traditional Java EE. For example, POJO’s that make application testable in TestNG or Junit use the new operator.

There is no way of passing the repository instance to service if instantiated with the new operator. Hence, we need to use Constructor Injection.

Example:

@Service
public class Employer {
private final Employee emp;
private final Designation desg;
public Employer(Employee emp, Designation desg) {
this.emp = emp;
this.desg = desg;
}
}

When a user provides a constructor with repositories as the parameters, Spring automatically injects into the service. Also, the repository fields can be made final as there is no need for change in them.

Boiler plate code can even be reduced using Lombak.

When the service class has final fields, Annotation @RequiredArgsConstructor will be automatically create a constructor with the parameters.

Applications of Spring Boot Unit Test

  • SpringBootUnitTest is a Spring Application Context that tests beyond what users would normally do with Vanilla Spring context.
  • It is an open-source micro-framework that is maintained by Pivotal company and provides Java users a platform to get working on configurable spring applications.
  • SpringBoot provides a huge number of annotations and utilities to help in the testing of applications.
  • In SpringBoot testing, unit testing is one done by developers to ensure each individual unit or the component functionalities are working as required.
  • There is an embedded server to avoid complexities in the application configuration.
  • Metrics and Health checks, and externalized configurations are some of the features of Spring Boot testing.
  • There are opinionated starter dependencies to simplify the build and the application configuration.
  • Users have an automatic config for Spring whenever needed.
  • Spring boot testing helps developers to start coding without wasting time in configuring the environment.
  • Compared to other Java frameworks, Spring Boot provides flexible configurations for testing database transactions and easier workflow with various tools.
  • As Spring Boot has access to a Command-line interface that develops and tests Spring applications built with Java agile.

Most of the developers use spring-boot-starter-test, which imports test modules and Junit, Hamcrest, AssertJ, and other such libraries.

If a user is using Junit 4, @RunWith(SpringRunner.class) is to be added to the test; else annotations get ignored.

If the user is using Junit 5, there is no need of adding @ExtendWith(SpringExtension.class) because @SpringBootTest and other @Test… annotations are annotated with it already.

Hamcrest is one of the frameworks for Unit Testing the software. It allows in checking the conditions in code using the existing matcher class and allows to define custom implementations.

Hence to use the Hamcrest framework in Junit, assertThat statement is used for one or several matches.

Conclusion

With this, we shall conclude the topic “Spring Boot Unit Test.” We have seen what Spring Boot Unit testing is and how it is implemented in Spring Boot applications. We have listed out the Mockito Unit Testing steps above. There are many other frameworks available for Spring boot unit testing. Also listed are our Applications of Spring boot unit testing. I hope this helps to decide which framework is easier to use while unit testing the applications. Thanks! Happy Learning!!

Recommended Articles

This is a guide to Spring Boot Unit Test. Here we discuss what Spring Boot Unit testing is and how it is implemented in Spring Boot applications. You may also have a look at the following articles to learn more –

  1. Spring Boot Batch
  2. Spring Boot Profiles
  3. Spring Boot Logging
  4. Spring Boot DevTools
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more