基于Junit5的MockMvc单元测试基础方法
package com.wangmh; import com.wangmh.controller.HelloController; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(HelloController.class) // 指定测试的控制器类 class SpringbootBlogApplicationTests { @Autowired private MockMvc mockMvc; @Test void contextLoads() throws Exception { mockMvc.perform(get("/hello")) // 模拟发送GET请求 .andExpect(status().isOk()) // 验证响应状态码为200 .andExpect(content().string("喜马拉雅山")); // 验证响应内容 } }