Reputation: 3
I have a hibernate SessionFactoryBean configured in my applicationContext which already has a real datasource as property. But i would like to use another local/mock datasource in my test class by overriding the actual datasource which was already injected to the sessionfactory.
The bean definition in the main application Context is like this.
<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>
I have a local datasource like this in my test case:
template = InitializeDataSource.getInitializedDataSource();
DataSource dataSource = template.getDataSource;
I need to override the injected datasource with the one in the bottom
Upvotes: 0
Views: 949
Reputation: 19
You can use profiles if your spring version is 3.1 or newer: Put your bean declaration inside a beans tag with profile
<beans profile="!test">
<bean id="pcfDataSource" ...>
...
</bean>
</beans>
Then in your test class you add "test" as your active profile
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "app-context.xml")
public class SampleTest
Finally you add your datasource configuration in the end of your test class
@Test
public void someTest() {
...
}
@Configuration
public class MockDataSourceConfig {
@Bean
public DataSource pcfDataSource() {
Template template = InitializeDataSource.getInitializedDataSource();
return template.getDataSource;
}
}
Upvotes: 1