例如一个员工管理系统,在测试使用PageHelp
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("/emps")
public String getEmps(@RequestParam(value = “pn”,defaultValue = “1”) Integer pn,
Model model){
PageHelper.startPage(pn,5);
List<Employee> emps=employeeService.getAll();
PageInfo page =new PageInfo(emps);
model.addAttribute("pageInfo",page);
return "list";
}
}``
这样的一个情况下,测试这个Controller
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:dispatcherServlet.xml"})
public class mvcTest {
// 传入Springmvc的ioc
@Autowired
WebApplicationContext context;
// 虚拟mvc请求,获取到处理结果。
MockMvc mockMvc;
//初始化
@Before
public void initMokcMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception {
//模拟请求拿到返回值
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1"))
.andReturn();
//请求成功以后,请求域中会有pageInfo;我们可以取出pageInfo进行验证
MockHttpServletRequest request = result.getRequest();
PageInfo pi = (PageInfo) request.getAttribute("pageInfo");
System.out.println("当前页码:" + pi.getPageNum());
System.out.println("总页码:" + pi.getPages());
System.out.println("总记录数:" + pi.getTotal());
System.out.println("在页面需要连续显示的页码");
int[] nums = pi.getNavigatepageNums();
for (int i : nums) {
System.out.print(" " + i);
}
//获取员工数据
List <Employee> list = pi.getList();
for (Employee employee : list) {
System.out.println("ID:" + employee.getEmpId() + "==>Name:" + employee.getEmpName());
}
}
}
```java