spring单元测试用于测试Mapper/Dao层的工作,推荐SPring项目使用Spring的单元测试,可以自定义注入我们需要的组件,步骤为:
1.导入SpringTest模块;
2.@ContextConfiguration指定Spring配置文件的位置;
3.直接@Autowired要使用的组件即可。
例子:
package com.xc.ssm.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.xc.ssm.bean.Department;
import com.xc.ssm.bean.Employee;
import com.xc.ssm.mapper.DepartmentMapper;
import com.xc.ssm.mapper.EmployeeMapper;
/**
-
测试mapper/dao层的工作
-
推荐Spring的项目就可以使用Spring的单元测试,可以自定注入我们需要的组件:
-
1.导入SpringTest模块;
-
2.@ContextConfiguration指定的SPring配置文件的位置;
-
3.直接Autowired要使用的组件即可。
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={“classpath:applicationContext.xml”})
public class MapperTest {/**
- @Autowired注解:自动装配mapper对象
*/
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;@Autowired
SqlSession sqlSession;@Test
public void testCRUD() {
//创建SpringIOC容器
/* ApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);
//从容器中获取Mapper
DepartmentMapper bean = ctx.getBean(DepartmentMapper.class);*/
// System.out.println(departmentMapper);
// System.out.println(bean);//插入部门数据——这两句是等价的,即bean和departmentMapper两个对象具有相同的作用 //bean.insertSelective(new Department(null,"python")); departmentMapper.insertSelective(new Department(null,"switch")); //生成员工数据
- @Autowired注解:自动装配mapper对象
// employeeMapper.insertSelective(new Employee(null,“kleine”,“M”,"kleine0426@163.com",4));
// System.out.println(“添加员工成功”);
//批量插入多个员工,使用可以执行批量操作的SqlSession
/*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+"@163.com",2));
}
System.out.println("批量操作完成");*/
}
}