Updated March 29, 2023
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:
- 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
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 –