Spring Boot MockMvc 测试配置指南
要使用 MockMvc 进行 Spring Boot 测试,需要执行以下配置步骤:
-
在测试类上加上注解
@RunWith(SpringRunner.class)和@WebMvcTest(YourController.class)。@RunWith(SpringRunner.class)使测试运行于 Spring 容器环境中,@WebMvcTest(YourController.class)表示只测试 YourController 类。 -
在测试类中注入 MockMvc 对象,并使用
MockMvcBuilders.standaloneSetup(YourController)方法初始化。 -
编写测试方法,在方法中使用 MockMvc 对象发送 HTTP 请求并验证响应结果。
示例代码:
@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class YourControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testYourMethod() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/yourUrl"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string('expectedResponse'));
}
}
其中,/yourUrl 是要测试的接口地址,expectedResponse 是预期的响应结果。
原文地址: https://www.cveoy.top/t/topic/nIeq 著作权归作者所有。请勿转载和采集!