关于单元测试,上一次就简单的概念和Mock基础做了,参考:
实际开发过程中,写单元测试是非常难的一件事情,其主要原因是代码结构不够好,导致单元测试不好写。特别是Dao层,因为Dao层代码都是与数据库相关的,所以我们在对Dao层代码进行单元测试的时候,不仅仅要考虑我在上篇文章中提到的代码隔离,还要注意单元测试不能带来脏数据。另外,dao层实例依赖spring上下文,我们怎么样来解决这个问题?看看下面的一个的测试实例:/*** @author lisanlai * Mail: * Blog: */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({ "/META-INF/spring/sellmanager-context.xml","/META-INF/spring/dao-context.xml","/META-INF/spring/mvc-context.xml" })//@Transactionalpublic class SysEmployeeDaoTest { /*** 测试deleteEmployee方法 .* Method Name:deleteEmployee .* the return type:void*/@Testpublic void deleteEmployee() { Employee employee = new Employee();employee.setEmployeeCode(""+new Date().getTime());employee.setEmployeeName("lisanlai");employee.setDelFlag("0");String empId = sysEmployeeDao.save(employee);Assert.assertNotNull("新增的员工ID为null",empId);//把该id对应的员工删除sysEmployeeDao.deleteEmployee(empId);//再用该ID去查数据库,如果为空,说明删除方法逻辑正确Employee emp = sysEmployeeDao.get(empId);Assert.assertNotNull(emp);Assert.assertArrayEquals("deleteEmployee方法逻辑不正确,员工没有被删除", new String[]{"1"}, new String[]{emp.getDelFlag()});//删除员工对象sysEmployeeDao.delete(emp);}/*** 测试saveEmployee方法 .* Method Name:saveEmployee .* the return type:void*/@Test@Transactional@Rollback(true)public void saveEmployee() { Employee employee = new Employee();employee.setEmployeeName("lisanlai");String empCode = ""+new Date().getTime();employee.setEmployeeCode(empCode);sysEmployeeDao.saveEmployee(employee);//通过code查找员工List emps = sysEmployeeDao.findByNamedParam(new String[]{"employeeCode"}, new String[]{empCode});Assert.assertTrue("saveEmployee方法逻辑错误,员工保存失败!", !emps.isEmpty());}}注意类上的三个注解://指定测试用例的运行器 这里是指定了Junit4 @RunWith(SpringJUnit4ClassRunner.class)//指定Spring的配置文件 路径相对classpath而言@ContextConfiguration({ "/META-INF/spring/sellmanager-context.xml","/META-INF/spring/dao-context.xml","/META-INF/spring/mvc-context.xml" })//如果在类上面使用该注解,这样所有的测试方案都会自动的 rollback//@Transactional再注意saveEmployee方法上的两个注解://这个注解表示使用事务@Transactional//这个表示方法执行完以后回滚事务,如果设置为false,则不回滚@Rollback(true)