spring boot單元測試之MockMvc


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM