|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
磨蹭了很久,终于开始用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) }} 返回类别: 教程 上一教程: 对身份证号码合法性的验证 下一教程: J2SE 5.0专题 之 语言特性 您可以阅读与"Spring下业务层的UnitTest--4.15更新"相关的教程: · Spring AOP之ThrowsAdvice · 测试spring的存储过程 · 使用Hibernate 和 Spring 实现一个事务持久层 · spring中DispatcherServlet的运行机制 · 各类Java资源收集(更新中……) |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |