@AutoConfigureMockMvc @RunWith(SpringRunner.class) @SpringBootTest public class ControllerTests { @Autowired MockMvc mvc; @Test public void get() throws Exception { mvc.perform( MockMvcRequestBuilders .get("/get")//maping .param("key", "val")//参数 .header("key", "val")//请求头 ) .andDo(MockMvcResultHandlers.print())//打印请求的详细信息 .andExpect(MockMvcResultMatchers.status().isOk())//判断返回status_code .andExpect(MockMvcResultMatchers.content().string("www.kagura.me") ); } @Test public void post() throws Exception { MvcResult mvcResult = mvc.perform( MockMvcRequestBuilders .post("/post")//maping .param("key", "val")//参数 .header("key", "val")//请求头 .content("请求体,比如JSON") .contentType(MediaType.APPLICATION_JSON_UTF8)//Content-Type .characterEncoding("UTF-8")//请求编码 ) .andDo(MockMvcResultHandlers.print())//打印请求的详细信息 .andExpect(MockMvcResultMatchers.status().isOk())//判断返回status_code .andExpect(MockMvcResultMatchers.content().string("www.kagura.me") ) .andReturn();//返回Response String contentAsString = mvcResult.getResponse().getContentAsString(); System.err.println(contentAsString); } }
未经允许不得转载:鹞之神乐 » Spring Boot用MockMvc单元测试示例