SSM框架的(CRUD)搭建Spring单元测试5.0

测试Mapper

在test文件夹下新建MapperTest.java测试类
1、准备工作:导入SpringTest模块,在pom.xml中添加


        
        
            org.springframework
            spring-test
            4.3.7.RELEASE
        

2、编写测试类

package com.christmaseve.crud.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.christmaseve.crud.dao.DepartmentMapper;

/**
 * 测试dao层的工作
 * @author zhangcheng
 *推荐使用Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件
 *1、导入SpringTest模块
 *2、@ContextConfiguration指定Spring配置文件的位置
 *3、直接autowired要使用的组件即可
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {
    
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    SqlSession sqlSession;
    /**
     * 测试DepartmentMapper
     */
    @Test
    public void testCRUD() {
//      //1、创建SpringIOC容器
//      ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//      //2、从容器中获取mapper
//      DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
        System.out.println(departmentMapper);
    }
}

3、进入Department.java,生成有参构造器和无参构造器

public Department() {
    super();
    // TODO Auto-generated constructor stub
}
public Department(Integer deptId, String deptName) {
    super();
    this.deptId = deptId;
    this.deptName = deptName;
}

4、进行插入部门操作测试

//1、插入几个部门
departmentMapper.insertSelective(new Department(null, "开发部"));
departmentMapper.insertSelective(new Department(null, "测试部"));

5、进入Employee.java,生成有参构造器和无参构造器

public Employee() {
    super();
    // TODO Auto-generated constructor stub
    }
public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
    super();
    this.empId = empId;
    this.empName = empName;
    this.gender = gender;
    this.email = email;
    this.dId = dId;
}

6、进行插入员工操作测试

//2、生成员工数据,测试员工插入
employeeMapper.insertSelective(new Employee(null,"Jerry","M", "[email protected]", 1));

7、关于批量操作,打开applicationContext.xml,添加代码如下


    
        
        
    

8、批量增添员工

EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
    for (int i = 0; i < 1000; i++) {
        String uid = UUID.randomUUID().toString().substring(0, 5) + i;
        mapper.insertSelective(new Employee(null, uid, "M", uid + "@zc.com", 1));
    }
System.out.println("批量完成");

你可能感兴趣的:(SSM框架的(CRUD)搭建Spring单元测试5.0)