Spring测试框架
Spring 测试框架是专门为测试基于 Spring 框架应用程序而设计的,它能够让测试用例非常方便地和 Spring 框架结合起来。
导入:Junit4(实际就是提供@Test,会自动导入;
注意:spring4.1.6只支持Junit4.9+hamcrest1.3)
spring-test-4.*(spring为测试而提供)
使用示例:
@ContextConfiguation(locations="/applicationContext.xml") //可应用多个,引用方法见解析@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)public class STest extends AbstractTransactionalJUnit4SpringContextTests{ //注意继承@Autowiredprivate ApplicationContext applicationContext; //注意:applicationContext通过注入进入private IService petService; //项目中的对象@Autowiredpublic void setPetService(IService petService) {this.petService = petService;}@Testpublic void testPet(){this.petService.add();}}
解析:
@ContextConfiguation注解中的属性:
1)locations:通过该属性指定 Spring 配置文件所在的位置,可以指定一个或多个。如下所示:
@ContextConfiguration(locations={“xx/yy/beans1.xml”,” xx/yy/beans2.xml”})
2)inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。
@TransactionConfiguration中的属性:
1)transactionManager指定spring的事务管理器,即我们所配置的声明式事务管理器的id
2)defaultRollback:是否回滚事务,默认为true表示回滚事务

浙公网安备 33010602011771号