SpringMVC 测试 Controller 示例

示例:模拟 /emps?pn=1 请求;拿到请求域;获取请求域对象;从请求域中拿对象

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:springMVC.xml"})
public class TestList {

    @Autowired
    WebApplicationContext context;

    MockMvc mockMvc;

    @Before // 注意是 Junit 的包
    public void initMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void testList() throws Exception {
//        模拟 `/emps?pn=1` 请求
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1"))
                .andReturn();
		
        // 获取请求域对象
        MockHttpServletRequest request = result.getRequest();
        // 从请求域中拿值
        PageInfo pageInfo = (PageInfo) request.getAttribute("pageInfo");
        
        for (Object employee : pageInfo.getList()) {
            System.out.println(employee);
        }
    }
}

posted @ 2021-11-02 10:11  yangruomao  阅读(63)  评论(0编辑  收藏  举报