磨蹭了很久,终于开始用UnitTest。原因一和大家一样,不想晚上做噩梦,原因二是在Spring下对业务层TDD,能够不需要Tomcat,完全摆脱对显示层开发进度的依赖,而专注快速的开发业务层。 但是我们也只在业务层使用UnitTest,因为MVC中显示层至今没有什么好的UnitTest方法(无论是不成才的httpUnit们还是笨重的GUI test工具),而我们的 业务逻辑又严格封装在业务层,Controler层只做个组装分派的基本动作,没必要花大力气去测试。 在Spring下的测试很简单,即使手写ApplicationContext的载入与Bean的创建都很简单,但在两方面Spring提供了更大的方便 1.bean的动态注入 本来自己手工load也不麻烦,但只要你的testCase继承Spring-mock.jar里的AbstractDependencyInjectionSpringContextTests, 你甚至只要把变量声明为protected,就会获得自动注入. 2.数据库环境的维持 Spring的解决方法也十分简单,他会为每个方法自动的,强制的rollback,这样就不存在清理-维持的问题了,只要你的testCase继承于 AbstractTransactionalDataSourceSpringContextTests. 同时,这个 AbstractTransactionalDataSourceSpringContextTests兼有上面AbstractDependencyInjectionSpringContextTests的功能. 3.进一步简化 一来这两个基类的名字都太长了, 二来还有一些公共的设定,比如在构造函数执行setPopulateProtectedVariables(true);这样子只要声明protected就会被动态注入,否则还要写setter才会被动态注入. 比如一些公共的context文件的定义. 所以我们抽象了一个基类 public class DAOTestCase extends AbstractTransactionalDataSourceSpringContextTests { protected ArrayList<String> contexts = null; public DAOTestCase() { //设了这个,就能autowire by name,否则by setter. setPopulateProtectedVariables(true); contexts = new ArrayList<String>(); contexts.add("/applicationContext-Hibernate.xml"); contexts.add("/applicationContext-SetupService.xml"); } public String[] getConfigLocations() { String[] tmp = new String[contexts.size()]; return contexts.toArray(tmp); } } 实际的子类 public class CustomerDAOTest extends DAOTestCase { protected CustomerDAO customerDAO; public void testGetCustomer() throws Exception { Customer customer = customerDAO.lookCustomer(1); assertEquals((int)customer.getCustomerNo(),1)
} }

|