但是我们也只在业务层使用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) }}
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!


