手机版
你好,游客 登录 注册
背景:
阅读新闻

使用 Spring 进行单元测试

[日期:2013-09-10] 来源:IBM  作者:赵 才文 [字体: ]

在测试类中基于 profile 加载测试 bean

从 Spring 3.2 以后,Spring 开始支持使用 @ActiveProfiles 来指定测试类加载的配置包,比如您的配置文件只有一个,但是需要兼容生产环境的配置和单元测试的配置,那么您可以使用 profile 的方式来定义 beans,如下:


清单 10. Spring-db.xml

 <beans xmlns="http://www.Springframework.org/schema/beans"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.Springframework.org/schema/beans 
 http://www.Springframework.org/schema/beans/Spring-beans-3.2.xsd"> 
 	 <beans profile="test"> 
 <bean id="datasource" 
 class="org.Springframework.jdbc.datasource.DriverManagerDataSource"> 
 <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> 
	 <property name="url" value="jdbc:hsqldb:hsql://localhost" /> 
	 <property name="username" value="sa"/> 
	 <property name="password" value=""/> 
	 </bean> 
</beans> 
	
<beans profile="production"> 
 <bean id="datasource" 
 class="org.Springframework.jdbc.datasource.DriverManagerDataSource"> 
	 <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> 
	 <property name="url" value="jdbc:hsqldb:hsql://localhost/prod" /> 
	 <property name="username" value="sa"/> 
	 <property name="password" value=""/> 
	 </bean> 
 </beans> 
 <beans profile="test,production"> 
 <bean id="transactionManager" 
     class="org.Springframework.jdbc.datasource.DataSourceTransactionManager"> 
	 <property name="dataSource" ref="datasource"></property> 
	 </bean> 
	 <bean id="initer" init-method="init" class="service.Initializer"> 
	 </bean> 
 <bean id="accountDao" depends-on="initer" class="DAO.AccountDao"> 
	 		 <property name="dataSource" ref="datasource"/> 
	 	 </bean> 
	 	
	 	 <bean id="accountService" class="service.AccountService"> 
	 	 </bean> 
	 	 <bean id="envSetter" class="EnvSetter"/> 
 	 </beans> 
 </beans> 

 

上面的定义,我们看到:

  • 在 XML 头中我们引用了 Spring 3.2 的 beans 定义,因为只有 Spring 3.2+ 才支持基于 profile 的定义
  • 在 <beans> 根节点下可以嵌套 <beans> 定义,要指定 profile 属性,这个配置中,我们定义了两个 datasource,一个属于 test profile,一个输入 production profile,这样,我们就能在测试程序中加载 test profile,不影响 production 数据库了
  • 在下面定义了一些属于两个 profile 的 beans,即 <beans profile=”test,production”> 这样方便重用一些 bean 的定义,因为这些 bean 在两个 profile 中都是一样的


清单 11. AccountServiceTest.Java

 @RunWith(SpringJUnit4ClassRunner.class) 
 @ContextConfiguration("/config/Spring-db.xml") 
 @Transactional 
 @ActiveProfiles("test") 
 public class AccountServiceTest { 
 ... 
 } 

 

注意上面的 @ActiveProfiles,可以指定一个或者多个 profile,这样我们的测试类就仅仅加载这些名字的 profile 中定义的 bean 实例。

linux
相关资讯       Spring  Spring单元测试  Spring测试 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款