springboot利用MockMvc测试controller控制器
主要记录一下控制器的测试,service这些类测试相对简单些(可测试性强)
API测试需求比较简单:
① 需要返回正确的http状态码 200
② 需要返回json数据,并且不能返回未经捕获的系统异常
测试不通过例子
此测试类的部分代码
package cn.taxiong.search.web.controller; import cn.taxiong.search.Application; import cn.taxiong.search.constant.ErrorCodeMsgEnum; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SearchControllerTest { private MockMvc mockMvc; @Autowired protected WebApplicationContext wac; @Before() //这个方法在每个方法执行之前都会执行一遍 public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象 } @Test public void shopSearch() throws Exception { mockMvc.perform( MockMvcRequestBuilders.get("/shopSearch").accept(MediaType.APPLICATION_JSON_UTF8) .param("page", "1") .param("pageSize", "2") .param("startDate", "2018-01-01") .param("endDate", "2028-01-01") .param("keyword", "较场尾") .param("lat", "22.22") .param("lon", "42.22") .param("distance", "5000") .param("capacity", "2") .param("style", "3") .param("gt", "1") .param("lt", "9900") .param("keywordScope", "0") .param("sort", "DEFAULT") .param("service", "{6,7}") .param("facilities", "{5,6}") .param("shopType", "1") .param("goodsCategory", "1") ) .andExpect(status().isOk()) // 判断返回状态 .andExpect(content().contentType("application/json;charset=UTF-8")) // 判断内容类型 .andExpect(jsonPath("$.code", Matchers.not(ErrorCodeMsgEnum.SYSTEM_ERROR.getCode()))) // 如果是系统异常(未捕获的异常),则测试不通过 .andDo(print()); //打印出请求和相应的内容 } }
测试通过例子:
当然,如果要返回码为正确的代码时才能测试通过可以这样写
// 判断只有返回状态码为0才通过 .andExpect(jsonPath("$.code").value(ErrorCodeMsgEnum.SUCCESS.getCode())) // 如果是系统异常(未捕获的异常),则测试不通过 //.andExpect(jsonPath("$.code", Matchers.not(ErrorCodeMsgEnum.SYSTEM_ERROR.getCode())))