开发者

How do I swap a jndi datasource lookup to an in memory database for intergration testing?

开发者 https://www.devze.com 2023-04-06 20:34 出处:网络
I\'m using Spring and Hibernate and want to do some intergration testing with DBUnit. In my application-context.xml I currently specify a datasource via jndi-lookup which reads the jndi-name from a pr

I'm using Spring and Hibernate and want to do some intergration testing with DBUnit. In my application-context.xml I currently specify a datasource via jndi-lookup which reads the jndi-name from a properties file:

开发者_运维问答<jee:jndi-lookup id="dataSource" 
   jndi-name="${datasource.myapp.jndi}"
   cache="true"
   resource-ref="true"
   proxy-interface="javax.sql.DataSource" />

I'd like to swap this out to an in memory database (hsqldb, h2 etc) for integration testing by just supplying a new properties file, is this possible? Or should I just use a different application-context.xml for the integration testing?


You can either have separate application contexts for prod and test or specify a default data source for the JNDI data source that should be used if the lookup fails. Then don't have a JNDI data source configured on your integration test environment. Spring will automatically fail over to the in-memory source when the lookup fails.


This is why Spring 3.1 introduced profiles: http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/

Upgrade application to 3.1 or use different configs for integrations tests.


Move the datasource bean definition to a separate config file (infrastructure-config.xml), create another version of it called test-infrastructure-config.xml in which you can define a datasource either using the jdbc:embedded-database tag

<jdbc:embedded-database type="hsql">
   <!-- in case you want to populate database, list the sql script files here -->
   <jdbc:script location=".."/>
   <jdbc:script location=".."/>
</jdbc:embedded-database>

Once you do this you specify the main application-context.xml and test-infrastructure-config.xml for out of conatiner testing and with the infrastructure-config.xml for deployment.


Use a @Bean to define your datasource. In that method you can use conditional logic to determine the environment and either do the JNDI lookup or connect to your in-memory DB.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号