spring单元测试之MockMvc,这个只是模拟,并不是真正的servlet,所以session、servletContext是没法用的。
@RunWith(SpringRunner.class) @SpringBootTest @WebAppConfiguration public class UrlTests { @Autowired private WebApplicationContext webContext; private MockMvc mockMvc; @Before public void setupMockMvc() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(webContext).build(); } @Test public void testGet() throws Exception { System.err.println("========================"); Cookie cookies = new Cookie("cookie", "cook"); mockMvc.perform(get("/index?name=xiaoming") .header("header", "hehe") .cookie(cookies) .requestAttr("name", "pangbin") .sessionAttr("name", "panggao") .characterEncoding("UTF-8")) .andExpect(status().isOk()) .andDo(MockMvcResultHandlers.print(System.err)) .andReturn(); System.err.println("========================"); } @Test public void testPost() throws Exception { System.err.println("========================"); mockMvc.perform(post("/index") .header("header", "hehe") .param("body", "baby!")) .andExpect(status().isOk()) .andDo(MockMvcResultHandlers.print(System.err)) .andReturn(); System.err.println("========================"); } }