在SSH中增加JUNIT4单元测试
首先,需要将UNITILS相关的jar包导入到系统的依赖jar包文件lib中,相关的jar文件如下:dbunit-2.4.8.jarhamcrest-all-1.3.0RC2.jarhamcrest-library-1.1.jarhtmlunit-2.8.jarhtmlunit-core-js-2.8.jarhttpclient-4.0.2.jarhttpcore-4.0.1.jarhttpmime-4.0.1.jarjunit-4.8.2.jarmockito-all-1.8.5.jarnekohtml-1.9.14.jaroperadriver-v0.6.jarselaid-1.0.1.jarselenium-java-2.4.0.jarspring-ws-test-0.22.jartestng-5.14.4.jarunitils-core-3.1.jarunitils-database-3.1.jarunitils-dbmaintainer-3.1.jarunitils-dbunit-3.1.jarunitils-mock-3.1.jarunitils-orm-3.1.jarunitils-spring-3.1.jarunitils-testng-3.1.jarxmlunit-1.2.jarxmlunit-1.3.jar此外,除了常见的jar包之外,还有一个commons-lang包也是需要的,具体报错的时候,在网上找一下就ok了.
然后,使用Eclipse的new功能,创建一个基于Junit4的test case,需要注意的事情是,需要让该test case能够得到spring 的SpringApplicationContext对象,得到了Spring的SpringApplicationContext对象之后,后面的测试用例就比较简单了.在获取SpringApplicationContext的时候,一定要注意注解里面的文件位置的获取.我们可以多看一下编译之后的文件,不要仅仅依据eclipse的文件的位置来判断相对位置.下面是我的Test Case的父类,以及子测试类:
package com.ziwen.common;
import org.springframework.context.ApplicationContext;import org.unitils.UnitilsJUnit4;import org.unitils.spring.annotation.SpringApplicationContext;
public class CommonTest extends UnitilsJUnit4{@SpringApplicationContext({"springConfig/applicationContext.xml","springConfig/bizContext.xml","springConfig/daoContext.xml"})private ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {return applicationContext;}
public void setApplicationContext(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}}
子类:package com.ziwen.biz;
import static org.junit.Assert.assertNotNull;
public class TestDemoBiz extends CommonTest{@SpringBean("demoBiz")private DemoBiz demobiz;@Testpublic void testDoSth() {List<Demo> list=demobiz.getDemoList(new Page(10));assertTrue(list.size()>1);}
@Testpublic void testGetDemoList() {String str=demobiz.doSth();assertNotNull(str);}
}
测试的结果:作者 陈字文(热衷于PM\ORACLE\JAVA等,欢迎同行交流)EMAIL:ziwen@163.com QQ:409020100