Friday, March 19, 2010

Loading properties into Spring context files during Spring JUnit tests

Spring has some rather handy JUnit test wrapper classes like AbstractSingleSpringContextTests.

Normally that is all great. All you need to do is override the getConfigLocations method with your context filename(s) and it will load the context(s) before running the tests. All your beans are now available to call in your unit test.

However, on a project I've been working on recently we place a lot of properties in our contexts that get overwritten at runtime depending on if we're running in development, pre-production or production (database connections etc). Loading these up as they in a Spring JUnit test causes all sorts of problems !

What we've done is create another small context file that we've called applicationContext-test.xml that looks like this -

  
<beans xmlns="http://www.springframework.org/schema/beans" xsi="http://www.w3.org/2001/XMLSchema-instance" util="http://www.springframework.org/schema/util" aop="http://www.springframework.org/schema/aop" context="http://www.springframework.org/schema/context" schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<!-- Ensures that all the properties defined in development.properties are loaded -->
<context:property-placeholder location="file:config/development.properties">

</context:property-placeholder></beans>



Then just add this to the start of the list of context files we list in getConfigLocations() and all your properties get loaded and used !

  
@Override protected String[] getConfigLocations() {
/*
* By including the applicationContext-test.xml it populates the parameters from the
* dev config file (see the applicationContext-test.xml file)
*/
return new String[] {
"applicationContext-test.xml", "applicationContext-mq.xml", "applicationContext-db.xml"
};
}

No comments: