springboot利用MockMvc測試controller控制器
阿新 • • 發佈:2018-07-31
ica 返回 protect exceptio charset ood 返回JSON數據 autowire utf-8
主要記錄一下控制器的測試,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 staticorg.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()); //打印出請求和相應的內容 } }
測試通過例子:
springboot利用MockMvc測試controller控制器