引入依赖
<!-- junit5 spring-test--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
编写测试类
package boot; 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 org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @SpringBootTest @AutoConfigureMockMvc public class MockMvcTest { @Autowired MockMvc mockMvc; //无需依赖web网络环境,无需启动应用,可直接请求controller @Test void testMockMVC() throws Exception { //发起一个模拟请求 mockMvc.perform( MockMvcRequestBuilders.get("/getUser") //发送get请求 .accept(MediaType.APPLICATION_JSON) //设置响应的文本类型 ) .andExpect(MockMvcResultMatchers.status().isOk())//断言状态码为200 .andDo(MockMvcResultHandlers.print()); } @Test void testMockMVCPost() throws Exception { mockMvc.perform( MockMvcRequestBuilders.post("/updateUser") //发送get请求 .accept(MediaType.APPLICATION_JSON) //设置响应的文本类型 .contentType(MediaType.APPLICATION_JSON_UTF8)//设置请求的文本类型 .content("{\"name\":\"lisi\",\"age\":20}") ).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("lisi"))//断言 .andDo(MockMvcResultHandlers.print()); } }
标签:web,org,springframework,import,test,mockMVC,servlet From: https://www.cnblogs.com/ixtao/p/17023468.html