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("========================");
    }
}

 

相关文章:

  • 2021-06-04
  • 2021-09-11
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2021-11-05
  • 2022-12-23
  • 2021-09-23
猜你喜欢
  • 2021-11-24
  • 2022-01-21
  • 2021-09-08
  • 2021-06-26
  • 2022-01-06
  • 2022-01-06
  • 2022-12-23
相关资源
相似解决方案