2007/10/12

SpringContextAware JUnit TestCase

In order to run Junit test case outside of a J2EE container, the test case need to initialize the Spring framework properly. I created this abstract class SpringContextAware, which extends from junit.framework.TestCase and initialize the Spring framework in it's setUp() method. User Test Cases that extends from this class will be running with Spring context loaded already.

public abstract class SpringContextAware extends TestCase {
public SpringContextAware(String name){
super(name);
}

public void setUp() throws Exception{
if (SpringApplicationContext.getApplicationContext()==null) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{
// list your context files here
"context-service.xml",
"context-hibernate.xml"
});
ctx.registerShutdownHook();
}
}

public void tearDown() throws Exception{
}
}


Here is the SpringApplicationContext class, basically it allows java classes not defined as a spring bean to be able to access the Spring Application Context.

public class SpringApplicationContext implements ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
return SpringApplicationContext.context;
}

/**
* This method is called from within the ApplicationContext once it is
* done starting up, it will stick a reference to itself into this bean.
*
* @param context a reference to the ApplicationContext.
*/
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringApplicationContext.context = context;
}

/**
*This is about the same as context.getBean("beanName"), except it has its
* own static handle to the Spring context, so calling this method statically
* will give access to the beans by name in the Spring application context.
* As in the context.getBean("beanName") call, the caller must cast to the
* appropriate target class. If the bean does not exist, then a Runtime error
* will be thrown.
*
* @param beanName the name of the bean to get.
* @return an Object reference to the named bean.
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}


This bean itself however, needs to be defined in the Spring Context XML file:

<!-- provide access to spring application context -->
<bean id="springApplicationContext" class="com.blah.blah.SpringApplicationContext">
</bean>


Any comments are welcome :)

No comments:

Well well... why another J2EE blog? I benefited from other people's technical blogs, and guess what, it's a good idea to contribute some of my works too. Hope it's helpful and useful, to all of your folks.