SSM_CRUD新手练习(7)Spring单元测试分页请求

          好久没写这个系列博客了是因为本人去公司实习去了,公司用的是Spring+SpingMvc+Hibernate现在有时间了不管怎么样继续把这个项目写完。

  因为机器的原因,我的环境变成了IDEA+oracle+1.8+tomcat8.5,不过不影响,只是数据库的配置不同和导入的是oracle的jar包罢了。

  那就继续吧,我们已经写了一个分页的后台控制器,和前面一样我们使用Spring单元测试有没有问题,能不能取出数据。

  在测试之前我们要知道,我们需要给后台的分页控制器发送一个请求,它才能处理这个请求给我们返回数据。Spring单元测试方便就在于它能模拟请求。

  在test目录下新建MvcTest文件:

package com.atguigu.crud.test;

import com.atguigu.crud.bean.Employee;
import com.github.pagehelper.PageInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.List;

/**
 * 使用Spring测试模块提供的测试请求功能,测试curd请求的正确性
 * Spring4测试的时候,需要servlet3.0的支持
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml","file:E:/project/ssm_crud/src/main/webapp/WEB-INF/dispatcherServlet-servlet.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","5")).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);
        }
        System.out.println();

        //获取员工数据
        List<Employee> list = pi.getList();
        for (Employee employee : list) {
            System.out.println("ID:" + employee.getEmpId() + "==>Name:" + employee.getEmpName());
        }
    }

}

  测试结果为:

  

 可以看到没有问题0.0

猜你喜欢

转载自www.cnblogs.com/fankailei/p/10028987.html