Introduction to Spring Boot Test
SpringBoot provides convenient testing functions, which can easily perform unit testing and integration testing. It mainly includes the following points:
- Spring Boot provides the @SpringBootTest annotation, which can be used to start Spring Boot applications for integration testing.
- Spring Boot provides the @MockBean annotation, which can be used to Mock Bean.
- Spring Boot provides the @SpyBean annotation, which can be used to spy beans.
- Spring Boot provides the @SpringBootConfiguration annotation, which can be used to declare configuration classes.
- Spring Boot provides support for AssertJ, which can be used to make assertions.
- Spring Boot provides test-related tool classes, such as TestRestTemplate and so on.
- SpringBoot provides @LocalServerPort, which can easily simulate the client and perform end-to-end integration testing on the running service
- SpringBoot provides automatic configuration of MockMvc, which is convenient for direct injection and use of MockMvc in test classes
rely
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Common Notes
@SpringBootTest
This annotation is used for integration testing and will start the entire Spring Boot application for end-to-end testing.
usage:
@SpringBootTest
public class MyTest {
// 测试方法
}
The test environment can be specified by the webEnvironment parameter:
-
MOCK: Load the Web Application Context without starting the Servlet container.
-
RANDOM_PORT: Load the Servlet container and use a random port.
-
DEFINED_PORT: Load the Servlet container and use the defined port.
-
NONE: Load the Web Application Context, but do not start the Servlet container.
@WebMvcTest
This annotation is used to test the Web layer, and will automatically inject the Bean of the Web layer, without starting the entire Spring Boot application.
usage:
@WebMvcTest(UserController.class)
public class MyTest {
@Autowired
private MockMvc mvc;
// 测试方法
}
@DataJpaTest
This annotation is used to test JPA-related beans, and will automatically configure Spring Data JPA-related beans.
usage:
javaCopy code@DataJpaTest
public class MyTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
// 测试方法
}
@MockBean
This annotation is used to Mock a Bean and inject it into the test class for Isolation testing.
usage:
javaCopy code@SpringBootTest
public class MyTest {
@MockBean
private UserService userService;
// 测试方法
}
@SpyBean
This annotation is used to spy a bean and inject it into the test class without affecting the real bean.
usage:
@SpringBootTest
public class MyTest {
@SpyBean
private UserService userService;
// 测试方法
}
@SpringBootConfiguration
This annotation is used to declare configuration classes, equivalent to @Configuration.
usage:
@SpringBootConfiguration
public class MyConfig {
// 配置代码
}
Can be used in test classes to load additional configuration classes.
@LocalServerPort
This is a very useful annotation to get the actual port number of the started embedded server instance for tests.
The main function and usage are as follows:
The server port number for automatic injection startup
In the test class, the @LocalServerPort annotation can be used like this:
javaCopy code@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
private int port;
// 测试方法可以使用port变量
}
In this way, you can get the randomly assigned port number.
Use in conjunction with @Value
@LocalServerPort can also be combined with @Value:
javaCopy code@Value("${local.server.port}")
private int port;
test endpoint
With the port number in hand, it can be verified by testing the endpoint:
javaCopy code@Autowired
private TestRestTemplate restTemplate;
@Test
public void test() {
String body = this.restTemplate.getForObject("http://localhost:" + port + "/hello", String.class);
assertEquals("Hello World", body);
}
mock client
Using @LocalServerPort can very conveniently simulate the client and perform end-to-end integration tests on running services.
@AutoConfigureMockMvc
This is a convenient annotation provided by Spring Boot, which can be used to automatically configure MockMvc to facilitate direct injection and use of MockMvc in test classes.
The main functions are as follows:
Automatically inject MockMvc
In the test class, you can directly inject MockMvc:
@Autowired
private MockMvc mvc;
No need to configure MockMvc yourself.
Use with @WebMvcTest
@AutoConfigureMockMvc is often used with @WebMvcTest to unit test controllers:
@WebMvcTest
@AutoConfigureMockMvc
public class TestController {
@Autowired
private MockMvc mvc;
@MockBean
private UserService userService;
@Test
public void test() throws Exception {
// 使用MockMvc进行请求测试
}
}
Simulate HTTP requests
With MockMvc, it is easy to simulate various HTTP requests to test controllers:
// GET
mvc.perform(get("/users"))
.andExpect(status().isOk());
// POST
mvc.perform(post("/users"))
.andExpect(status().isCreated());
// 模拟参数
mvc.perform(get("/users").param("name", "test"))
.andExpect(content().string(containsString("test")));
validation response
The response result can be verified by MockMvc:
mvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.name").value("Test User"));
In short, @AutoConfigureMockMvc can flexibly simulate HTTP requests and verify responses, making it very convenient to test the Web layer. It is usually used in conjunction with the @WebMvcTest annotation, which provides great convenience for Spring Boot testing.
write at the end
If you are interested in related articles, you can pay attention to the official account "Architecture Hall", and will continue to update AIGC, java basic interview questions, netty, spring boot, spring cloud and other series of articles, and a series of dry goods will be delivered at any time!