Spring下业务层的UnitTest--4.15更新

王朝java/jsp·作者佚名  2006-01-09
宽屏版  字体: |||超大  

磨蹭了很久,终于开始用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)

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有