【问题标题】:Overriding datasource of a hibernate sessionfactory in test cases在测试用例中覆盖休眠会话工厂的数据源
【发布时间】:2015-11-23 22:15:38
【问题描述】:

我在我的 applicationContext 中配置了一个休眠的 SessionFactoryBean,它已经有一个真实的数据源作为属性。但是我想通过覆盖已经注入 sessionfactory 的实际数据源,在我的测试类中使用另一个本地/模拟数据源。

主应用Context中的bean定义是这样的。

<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
            abstract="false" scope="singleton" lazy-init="default" autowire="default">
        <property name="dataSource" ref="pcfDataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">$`db.hibernate.dialect}   </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
            </props>
        </property>
</bean>

我的测试用例中有一个像这样的本地数据源:

template = InitializeDataSource.getInitializedDataSource();
DataSource dataSource = template.getDataSource; 

我需要用底部的数据源覆盖注入的数据源

【问题讨论】:

  • 你可以看看使用java配置文件。

标签: java spring hibernate unit-testing sessionfactory


【解决方案1】:

如果您的 spring 版本是 3.1 或更高版本,您可以使用配置文件: 将您的 bean 声明放在带有配置文件的 beans 标记中

<beans profile="!test">
     <bean id="pcfDataSource" ...>
          ...
     </bean>
</beans>

然后在您的测试课程中添加“测试”作为您的活动资料

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "app-context.xml")
public class SampleTest

最后,在测试类的末尾添加数据源配置

@Test
public void someTest() {
     ...
}

@Configuration
public class MockDataSourceConfig {
    @Bean
    public DataSource pcfDataSource() {
        Template template = InitializeDataSource.getInitializedDataSource();
        return template.getDataSource; 
    }
}

【讨论】:

  • Gargarao,感谢您的回复,但我需要一个带有覆盖数据源的会话工厂,我认为这只是返回给我一个数据源
  • 我的错!我编辑显示如何分析数据源。这样,当 spring 寻找要在会话工厂中注入的 bean 时,它将获得在测试类中配置的那个
猜你喜欢
  • 2013-10-21
  • 2011-02-01
  • 2015-03-18
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
相关资源
最近更新 更多