MocMvc 我的测试终于成功了,坚持就是胜利
pom.xml
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-test</artifactId> 4 <scope>test</scope> 5 </dependency>
Controller
package com.wangfei.learn; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class HelloWorldController { @RequestMapping("/getHello") public String getHello(@RequestParam(value = "name") String name){ return "Hello " + name + "!"; } }
Test
快速创建测试类:在Controller层,将光标落在类名上,按住alt+enter,选中创建测试,选中相应的方法。
package com.wangfei.learn; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; 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.MvcResult; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @SpringBootTest class HelloWorldControllerTest { private MockMvc mockMvc; // 初始化MockMvc @BeforeEach void setUp(WebApplicationContext wac) { // 方式1:明确指定需要测试的“Controller”类 // this.mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build(); // 方式2:基于Spring容器进行配置,包含了Spring MVC环境和所有“Controller”类。 this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test void getHello() throws Exception{ // getHello()方法传递参数 MvcResult result = this.mockMvc.perform(get("/hello/getHello") .param("name", "王菲")//设置参数,如果参数需要json数据的话,就要改变请求数据类型为相应的 .contentType(MediaType.APPLICATION_FORM_URLENCODED)//设置请求数据类型 .accept(MediaType.APPLICATION_JSON))//设置返回数据类型 .andExpect(MockMvcResultMatchers.status().isOk())//检查返回状态 .andDo(MockMvcResultHandlers.print())//打印返回内容 .andReturn();//返回数据 //System.out.println(result.getResponse().getContentAsString());//打印返回的内容,中文可能会乱码,可以保持返回数据类型和请求数据类型一致 } }
结果


浙公网安备 33010602011771号