一、引入測試依賴包java
二、編寫測試類(GET請求)git
@RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup(){ //讓每一個測試用例啓動以前都構建這樣一個啓動項 mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenQueryUserAll() throws Exception{ //MockMvcRequestBuilders構建GET請求 mockMvc.perform(MockMvcRequestBuilders.get("/user") //請求參數 .param("token", "asfsafqfEQFFA$@%%4") //請求編碼和數據格式爲json和UTF8 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望的返回值 或者返回狀態碼 .andExpect(MockMvcResultMatchers.status().isOk()); //指望獲取返回值的具體 什麼參數 或者具體某個字段的值 具體在GitHub 搜jsonPath 什麼參數的什麼value //.andExpect(MockMvcResultMatchers.jsonPath("$.User.userName").value("zyy")); } }
https://github.com/json-path/JsonPathgithub
三、編寫測試類(POST請求)web
@RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup(){ //讓每一個測試用例啓動以前都構建這樣一個啓動項 mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void greatUserWhithDetailView() throws Exception{ String content = "{\"userName\":\"二十歲之後\",\"passWord\":null,\"id\":88}"; //MockMvcRequestBuilders構建GET請求 String result = mockMvc.perform(MockMvcRequestBuilders.post("/user") //請求編碼和數據格式爲json和UTF8 .contentType(MediaType.APPLICATION_JSON_UTF8) //請求的參數,爲json的格式 .content(content)) //指望的返回值 或者返回狀態碼 .andExpect(MockMvcResultMatchers.status().is5xxServerError()) //返回請求的字符串信息 .andReturn().getResponse().getContentAsString(); System.out.println(result); } }