一.加入依赖包
使用spring的测试框架需要加入以下依赖包:
JUnit 4 (官方下载:http://www.junit.org/)
Spring Test (Spring框架中的test包)
Spring 相关其他依赖包(不再赘述了,就是context等包)
如果使用maven,在基于spring的项目中添加如下依赖:
二.创建测试类
1)基类,其实就是用来加载配置文件的
解释下用到的注解:
@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
@ContextConfiguration({"classpath:applicationContext.xml","classpath:spring/buyer/applicationContext-service.xml"})
导入配置文件,这里我的applicationContext配置文件是根据模块来分类的。如果有多个模块就引入多个“applicationContext-service.xml”文件。如果所有的都是写在“applicationContext。xml”中则这样导入:
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!
@Transactional:这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
AbstractTransactionalDataSourceSpringContextTests要想构建这一系列的无污染纯绿色事务测试框架就必须找
到这个基类!(即所有事务均不生效)
2)接着是我们自己的测试类三.通过JUnit 4 执行
右键方法名,选择则“Run As”→“JUnit Test”即可
---------------------------------------------------------------------------------------------------------------------
然而当我执行时却报了第一个错误(之所以说是第一个是因为后面还有其他错误),错误内容如下:
上网查了一下,一般的解决方案是,换一个低一点的版本就好了。还有人说,是缺少hamcrest的包。去官网又看了一下,结果发现这样一段话:
junit.jar: Includes the Hamcrest classes. The simple all-in-one solution to get started quickly.Starting with version 4.11, Hamcrest is no longer included in this jar.
junit-dep.jar: Only includes the JUnit classes but not Hamcrest. Lets you use a different Hamcrest version.
注意部分的字,说明4.1.1中没有hamcrest包了。
最好的解决方法是:
使用是导入包的方案:junit.jar + hamcrest-core.jar + hamcrest-library.jar或者是:junit-dep.ajr+hancrest-all.jar
再次运行,又报错了,错误如下:
一点点搜吧,万能的stackoverflow啊,哈哈,老外同仁给出的解释:
Note that the Java 8 bytecode level (-target 1.8, as required by -source 1.8) is only fully supported as of Spring Framework 4.0. In particular, Spring 3.2 based applications need to be compiled with a maximum of Java 7 as the target, even if they happen to be deployed onto a Java 8 runtime. Please upgrade to Spring 4 for Java 8 based applications.
大概的意思就是java1.8版本只支持spring4.0以上。所以解决方法有2中①把sping版本换成4.0以上②把jdk调低点。
此处我选择把jdk调低点,再次运行,结果如下: