MockMVC使用总结

基础

  • controller:
@Controller
public class EmploeeController { 
    @Autowired
    EmploeeService emploeeService;
    /**
     * @return
     * 查询员工数据(分页查询)
     */
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,
            Model model) {
        PageHelper.startPage(pn, 5);
        List emps=emploeeService.getAll();
        PageInfo page=new PageInfo(emps,5);
        model.addAttribute("pageInfo",page);
        return "list";
    }
}
  • service:
@Service
public class EmploeeService {
    @Autowired
    EmploeeMapper emploeeMapper;
    public List getAll() {
        // TODO Auto-generated method stub
        return emploeeMapper.selectByExampleWithDept(null);
    }

}
  • dao:
List selectByExampleWithDept(EmploeeExample example);
  • mapper:



  
    
    
    
    
    
    
        
        
    
  


    e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
  



  • 数据库表结构


    MockMVC使用总结_第1张图片
    图片.png

测试部分

  • MVCTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class MVCTest {
    @Autowired
    WebApplicationContext context;
    MockMvc mockMVC;
    @Before
    public void initMockMvc() {
        mockMVC=MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void testPage() throws Exception {
        MvcResult result=mockMVC.perform(MockMvcRequestBuilders.get("/emps").param("pn","1")).andReturn();
        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 list=pi.getList();
        for(Emploee emploee:list) {
            System.out.println("ID:"+emploee.getEmpId()+"==>Name:"+emploee.getEmpName());
        }
    }
}
  • 返回展示数据
当前页码:1
总页码:21
总记录数:102
当前页面需要连续显示的页码:
 1 2 3 4 5ID:1==>Name:Tom
ID:2==>Name:Tom
ID:3==>Name:d4a8b0
ID:4==>Name:590b31
ID:5==>Name:ed92b2

总结

  • 测试代码关键部分
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class MVCTest {
    @Autowired
    WebApplicationContext context;
    MockMvc mockMVC;
    @Before
    public void initMockMvc() {
        mockMVC=MockMvcBuilders.webAppContextSetup(context).build();
    }
  • 意义
    简化测试流程,不用直接生成网络请求环境,Mock方式模拟HTTP请求。

你可能感兴趣的:(MockMVC使用总结)