Published in: Java
This Loader enables the loading of a custom context when using Spring JUnit runner, this enables programmatic registration of beans of commonly used beans in tests. This loader receive TestedService annotation in the processLocations method and uses its values to register beans in the loadContext method. This snippets completes the following entry: http://javadevelopmentforthemasses.blogspot.com/2008/07/mocking-spring-tests.html
public class Loader implements ContextLoader { private Class testedService; private Class[] beans; @Override TestedService annotation = testClass.getAnnotation(TestedService.class); testedService = annotation.service(); beans = annotation.beans(); return locs; } @Override GenericApplicationContext ctx = new GenericApplicationContext(); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); xmlReader.loadBeanDefinitions(new ClassPathResource("spring/context.xml")); final Map<String, Object> declaredValues = new HashMap<String, Object>(1); final String serviceName = StringUtils.uncapitalize(testedService.getSimpleName().replace("Impl", "")); register(serviceName, testedService, declaredValues,ctx); declaredValues.put("mocksHolder", testedService); register("autoBeanDeclarer", AutoBeanDeclarer.class, declaredValues,ctx); for (final Class bean : beans) {// registering all the other beans register(beanName, bean, declaredValues,ctx); } AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx); ctx.refresh(); return ctx; } private void register(final String name, final Class clazz, Map<String, Object> values,GenericApplicationContext ctx) { final BeanDefinitionBuilder serviceBuilder = BeanDefinitionBuilder.rootBeanDefinition(clazz); serviceBuilder.addPropertyValue(entry.getKey(), entry.getValue()); } values.clear(); ctx.registerBeanDefinition(name, serviceBuilder.getRawBeanDefinition()); } } // Usage, note that the location String has to be unique in order to make spring load the context separately for each test. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = Loader.class,locations="SomeUniqueString") @TestedService(service = SomeServiceImpl.class) public class SomeServiceCases { // tests and autowiring.. }
You need to login to post a comment.
