When writing unit tests in a system that uses Spring dependency injection, you often want Null or Fake instances of adapters to external systems as a matter of course. This may lead you to use a different Application Context XML file for your unit test suites. Most of the time, generic fakes are good enough, but sometimes you'll want to subsequently override particular settings with fakes that provide more visibility into the workings of the application. For this, load a specific context over the generic one.

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class SpringUnitTestSetup {

        private static BeanFactory beanFactory;

        public static void loadDefault() {
                String path = "/com/idiacomputing/application/TestApplicationContext.xml";
                load(path);
        }

        public static void load(String path) {
                Resource res = new ClassPathResource(path);
                beanFactory = new XmlBeanFactory(res);
        }

        public static Object getBean(String beanName) {
                return beanFactory.getBean(beanName);
        }

}


CategoryCheatSheet

iDIAcomputing: TddAndSpringDependencyInjection (last edited 2009-07-27 18:25:24 by localhost)