1.ContextConfiguration加载配置文件的时候,也要加载SpringMvc的配置文件
2.模拟请求的时候需要一个很重要的对象org.springframework.test.web.servlet.MockMvc MockMvc,该对象被初始化时需要方法 MockMvcBuilders.webAppContextSetup(context).build();来创建, 而context是Spring容器本身,获取方式为:在该测试类类名上添加注解@WebAppConfiguration,然后给WebApplicationContext context对象添加注解@AutoWired。
3.使用mockMvc对象进行模拟请求时,使用它的perform方法进行模拟
4.传一段代码,省的以后忘了
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试 @WebAppConfiguration @ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/springDispatcherServlet-servlet.xml"}) //加载配置文件 public class MvcTest { //虚拟请求 MockMvc mockMvc; //传入springMvc的IOC @Autowired WebApplicationContext context; @Before public void init() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { //模拟请求拿到返回值 MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5")).andReturn(); //请求成功以后,请求域中会有PageInfo,我们来取出pageInfo进行验证 MockHttpServletRequest request = result.getRequest(); PageInfo<Employee> pageInfo = (PageInfo) request.getAttribute("pageInfo"); System.out.println("当前页码:"+pageInfo.getPageNum()); System.out.println("总页码:"+pageInfo.getPages()); System.out.println("总记录数:"+pageInfo.getTotal()); System.out.println("在页面上需要连续显示的页码:"); int[] navigatepageNums = pageInfo.getNavigatepageNums(); for (int i : navigatepageNums) { System.out.println(i); } List<Employee> list = pageInfo.getList(); for (Employee employee : list) { System.out.println(employee); } } }