EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign up
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot Unit Test

Spring Boot Unit Test

Updated March 29, 2023

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.

ADVERTISEMENT
Popular Course in this category
SPRING BOOT Course Bundle - 5 Courses in 1 | 6 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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,

<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 ……
}
}

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
ADVERTISEMENT
MICROSOFT POWER BI Course Bundle - 8 Courses in 1
34+ Hours of HD Videos
8 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
CYBER SECURITY & ETHICAL HACKING Course Bundle - 13 Courses in 1 | 3 Mock Tests
64+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
MICROSOFT AZURE Course Bundle - 15 Courses in 1 | 12 Mock Tests
63+ Hour of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
KALI LINUX Course Bundle - 6 Courses in 1
20+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • 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

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

EDUCBA

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

Let’s Get Started

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

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

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

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

Forgot Password?

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

🚀 Extended Cyber Monday Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW