In this article, we will be discussing Testing in Spring Boot. There are so many different testing approaches in Spring Boot used for deploying the application server. Testing in Spring Boot is an important feature of software development which ensures that your application behaves as per the requirement and meets all the testing criteria. Spring Boot provides a robust testing framework that supports Unit Testing, Integration Testing, and End-to-End Testing.
1. Unit Tests:
- The Focus is on testing individual components or units of the code in isolation.
- Use tools like JUnit and Mockito for the writing unit tests.
2. Integration Tests:
- Test the interactions between the multiple components or modules.
- Ensures that different parts of the application work together perfectly.
- Typically involves testing repositories, services, and controllers.
3. End-to-End (E2E) Tests:
- Test the entire application from the end to end simulating real user scenarios.
- Involve testing application's behavior through its external interfaces.
- Use tools like Selenium for the web applications.
Testing Annotations in Spring Boot
@SpringBootTest:
- Indicates that the annotated class is the Spring Boot test.
- The Loads the complete application context.
@SpringBootTest
public class MySpringBootTest {
// Test methods go here
}
@RunWith(SpringRunner.class):
- The Specifies the class to run the tests.
- The SpringRunner is the alias for SpringJUnit4ClassRunner.
@RunWith(SpringRunner.class)
@SpringBootTest
public class MySpringBootTest {
// Test methods go here
}
@MockBean:
- The Mocks a Spring Bean for testing purposes.
- Useful for the isolating the unit of the code being tested.
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private ExternalService externalService;
// Test methods go here
}
@Test:
- The Denotes a test method.
- Executed when running the test class.
@Test
public void myUnitTest() {
// Test logic goes here
}
Maven Dependencies for Testing
To get started with the testing in the Spring Boot project you need to include the following dependencies in the your pom.xml file:
<dependencies>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
JUnit Testing Dependency
The Spring Boot uses JUnit as the default testing framework. The spring-boot-starter-test dependency already includes the JUnit so you don't need to add it explicitly.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
1. @SpringBootTest (Integration Testing)
The @SpringBootTest is a core annotation in Spring Boot for the integration testing. It can be used to the specify the configuration of ApplicationContext for the your tests.
Let's consider a simple controller class:
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
Now, let's write a test class:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}
Explanation:
- @RunWith(SpringRunner.class):The Specifies the runner that JUnit should use to run the tests. The SpringRunner is the new name for the SpringJUnit4ClassRunner.
- @SpringBootTest: Used to indicate that the annotated class is the Spring Boot test class.
Property File Configuration:
For testing, you might want to have a separate the application-test.properties file. The Spring Boot automatically picks up properties from this file during the tests.
2. @TestConfiguration (Test Configuration)
The @TestConfiguration is used to the specify additional configuration for the tests. It is often used to define @Bean methods for the test-specific beans.
@TestConfiguration
public class TestConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
3. @MockBean (Mocking)
The @MockBean is used to mock a bean of the specific type, making it convenient to test components that depend on bean.
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private ExternalService externalService;
@Test
public void testServiceMethod() {
// Define behavior for the mocked external service
when(externalService.getData()).thenReturn("Mocked Data");
// Now test the method from MyService that uses externalService
String result = myService.processData();
assertEquals("Processed: Mocked Data", result);
}
}
4. @WebMvcTest (Unit Testing)
The @WebMvcTest is used for the testing the controllers in the Spring MVC application. It focuses only on MVC components.
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerWebMvcTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}
5. @DataJpaTest (Integration Testing)
The @DataJpaTest is used for the testing JPA repositories. It focuses only on the JPA components.
@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {
@Autowired
private MyRepository myRepository;
@Test
public void testRepositoryMethod() {
MyEntity entity = new MyEntity();
entity.setData("Test Data");
myRepository.save(entity);
MyEntity savedEntity = myRepository.findById(entity.getId()).orElse(null);
assertNotNull(savedEntity);
assertEquals("Test Data", savedEntity.getData());
}
}
Additional Annotations
- @AutoConfigureMockMvc: Used with the @SpringBootTest to automatically configure a MockMvc instance.
- @DirtiesContext: Indicates that the ApplicationContext associated with test is dirty and should be closed after the test.
- @Transactional: Used to indicate that a test-managed transaction should be used.
Conclusion
The Spring Boot's testing support combined with the popular testing libraries like JUnit and Mockito enables the developers to create comprehensive test suites for their applications. By using the appropriate testing annotations and strategies you can ensure the reliability and correctness of the your Spring Boot applications.
Similar Reads
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Spring Boot - Starter Test
Spring Boot is built on top of the spring and contains all the features of spring. It 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.
5 min read
Spring Boot - Getting Started
Spring Boot is a part of the larger Spring Framework ecosystem which is known for its comprehensive programming and configuration model for the modern Java-based enterprise applications. Spring Boot has emerged as a go-to framework for creating REST APIs, microservices, and web applications with les
5 min read
Book Inventory System Using Spring Boot
The Book Inventory System in Spring Boot plays an important role in Business logic. Mostly the online Book Inventory System is developed with the required business logic. Here we created a simple Spring Boot Application for the Book Inventory System, This application provides basic functionalities f
15+ min read
Spring Boot - Caching
Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which e
6 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 natu
8 min read
Spring Boot - Starter Parent
Spring Boot Starter Parent is a starter project that provides the default configuration for spring-based applications. It is added as a parent in the pom.xml file. The spring-boot-starter-parent defines spring-boot-dependencies as its parent. The spring-boot-starter-parent inherits dependency manage
3 min read
Introduction to Spring Boot
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read
Spring WebFlux Testing
In Spring Boot, Spring WebFlux is the reactive programming framework that can provide support for the building of asynchronous, non-blocking, and event-driven applications when it comes to testing in the spring WebFlux. Key Terminologies:Unit Testing: It can involve testing individual components of
9 min read
Scenario in Cucumber Testing
Cucumber is a popular open-source testing tool that supports Behavior Driven Development (BDD). It facilitates the testing of software by providing a way of describing the behavior of the software in plain English. Of the various components of Cucumber, the âScenarioâ is one of the most basic struct
5 min read