SSM_CRUD新手练习(5)测试mapper

上一篇我们使用逆向工程生成了所需要的bean、dao和对应的mapper.xml文件,并且修改好了我们需要的数据库查询方法。

现在我们来测试一下DAO层,在test包下新建一个MapperTest.java类

package com.atguigu.crud.test;

import java.util.UUID;

import org.apache.ibatis.session.SqlSession;
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.atguigu.crud.bean.Department;
import com.atguigu.crud.bean.Employee;
/*测试dao层的工作
 * 推荐使用Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件
 * 1.导入SpringTest模块
 * 2.@ContextConfigurtion指定配置文件的位置
 * 3.@RunWith指定哪个模块来运行单元测试
 * 4.直接autowired要使用的组件即可
 */
import com.atguigu.crud.dao.DepartmentMapper;
import com.atguigu.crud.dao.EmployeeMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class MapperTest {
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    SqlSession sqlSession;
    @Test
    public void testCRUD() {
        /*不用JUnit测试的方法
         * 1.创建springIoc容器
         * 2.从容器中获取mapper
         * 
         * ApplicationContext ioc= new ClassPathXmlApplicationContext("ApplicationContext.xml");
           DepartmentMapper bean=ioc.getBean(DepartmentMapper.class);
           System.out.println(bean.selectByPrimaryKey(1).getDeptName());
        */
        System.out.println(departmentMapper);
        //插入几个部门
        //departmentMapper.insertSelective(new Department(null,"研发部"));
        //departmentMapper.insertSelective(new Department(null,"产品部"));
        //插入员工表
        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+"atguigu.com",1));
        }
   
    }
    
}

代码我都做了注释,我们平常测试用的方法就是创建一个ioc容器,再用它取到mapper对象,调用mapper中的方法操作数据库。

现在我们使用SpringJUnit测试模块进行测试,只要配置好文件,就可以直接Autowired使用的组件。

需要注意的是,为了插入数据方便,我们需要在Department.java和Employee.java中添加有参和无参构造方法。

在添加Employee有参构造方法时,记得去掉Deparment参数,我们并不需要传入它。

我们使用了可以执行批量操作的SqlSession进行批量插入数据,SqlSession我们在applicationContext.xml已经配置了。员工名使用UUID命名方法。

 </bean>
    <!-- 配置一个可以批量操作的sqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    <constructor-arg name="executorType" value="BATCH"></constructor-arg>
   </bean>

现在我们测试MapperTest.class执行结果就可以在数据库中看到了。

猜你喜欢

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