Spring Boot 3.x Web单元测试最佳实践
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void givenRequestToHomePage_whenHomePageExists_thenCorrectResponse() throws Exception {
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(status().reason(containsString("Welcome")));
}
}
这个代码实例展示了如何使用Spring Boot 3.x的Spring Test & Spring MVC Test框架来测试一个Web控制器的基本功能。使用@SpringBootTest
来启用Spring Boot的自动配置,并且使用@AutoConfigureMockMvc
来自动配置MockMvc实例。然后,使用MockMvc的perform
方法来发送一个模拟的HTTP GET请求到应用程序的根路径"/",并验证返回的状态是200 OK以及响应中包含"Welcome"字样。
评论已关闭