In this quick article, we will learn how to use @SpringBootTest annotation to perform Integration testing in Spring boot applications.
Spring Boot provides @SpringBootTest annotation for Integration testing.
In this tutorial, we will use the MySQL database for Integration testing
Let's first take a look at the overview of @SpringBootTest annotation.
@SpringBootTest Annotation
- MOCK(Default): Loads a web ApplicationContext and provides a mock web environment.
- RANDOM_PORT: Loads a WebServerApplicationContext and provides a real web environment. The embedded server is started and listened to a random port. This is the one that should be used for the integration test.
- DEFINED_PORT: Loads a WebServerApplicationContext and provides a real web environment. NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment.
So basically, the @SpringBootTest annotation tells Spring Boot to look for the main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context.
@SpringBootTest Annotation Example
Create Spring Boot Application
- Spring Web
- Spring Data JPA
- Lombok
- MySQL Driver
Configure MySQL database
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto = create-drop
Create JPA Entity
package net.javaguides.spirngboot.entity;
import lombok.*;
import jakarta.persistence.*;
@Setter
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
private String email;
}
Create Spring Data JPA Repository
package net.javaguides.spirngboot.repository;
import net.javaguides.spirngboot.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Create Spring Boot REST Controller
package net.javaguides.spirngboot.controller;
import net.javaguides.spirngboot.entity.Student;
import net.javaguides.spirngboot.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Student createStudent(@RequestBody Student student){
return studentRepository.save(student);
}
@GetMapping
public List<Student> getAllStudents(){
return studentRepository.findAll();
}
}
Create Integration Tests with MySQL database
package net.javaguides.spirngboot;
import net.javaguides.spirngboot.entity.Student;
import net.javaguides.spirngboot.repository.StudentRepository;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.util.List;
@SpringBootTest
@AutoConfigureMockMvc
class SpringbootTestcontainersDemoApplicationTests {
@Autowired
private StudentRepository studentRepository;
@Autowired
private MockMvc mockMvc;
// given/when/then format - BDD style
@Test
public void givenStudents_whenGetAllStudents_thenListOfStudents() throws Exception {
// given - setup or precondition
List<Student> students =
List.of(Student.builder().firstName("Ramesh").lastName("faadatare").email("ramesh@gmail.com").build(),
Student.builder().firstName("tony").lastName("stark").email("tony@gmail.com").build());
studentRepository.saveAll(students);
// when - action
ResultActions response = mockMvc.perform(MockMvcRequestBuilders.get("/api/students"));
// then - verify the output
response.andExpect(MockMvcResultMatchers.status().isOk());
response.andExpect(MockMvcResultMatchers.jsonPath("$.size()", CoreMatchers.is(students.size())));
}
}
@Autowired
private MockMvc mockMvc;
ResultActions response = mockMvc.perform(MockMvcRequestBuilders.get("/api/students"));
// then - verify the output
response.andExpect(MockMvcResultMatchers.status().isOk());
response.andExpect(MockMvcResultMatchers.jsonPath("$.size()", CoreMatchers.is(students.size())));
Run Integration Test
Conclusion
In this tutorial, we have seen the overview of @SpringBootTest annotation and we have also created a simple example to demonstrate the usage of @SpringBootTest annotation in the Spring boot application.
Related Spring Boot Testing Tutorials and Guides
- Spring Boot Testing - Data Access Layer Integration Testing using Testcontainers
- Spring Boot Testing - REST API Integration Testing using Testcontainers
- Spring Data JPA Repository Testing using Spring Boot @DataJpaTest
- CRUD JUnit Tests for Spring Data JPA - Testing Repository Layer
- Spring Boot Unit Testing CRUD REST API with JUnit and Mockito
- Spring Boot Integration Testing MySQL CRUD REST API Tutorial
- Spring Boot Unit Testing Service Layer using JUnit and Mockito
Comments
Post a Comment
Leave Comment