使用SpringJUnit4ClassRunner自定义BeanFactory?

kro*_*old 8 java spring

通过创建缓存bean工厂终于解决了类型问题慢速自动装配问题.

我真的希望能够将这样的CachingByTypeBeanFactory与SpringJUnit4ClassRunner一起用于使用@Autowired运行JUnit测试.但似乎无法通过ContextLoader在应用程序上下文中更改Bean Factory.

有没有其他方法可以做到这一点?

ger*_*tas 8

创建自己的ContextLoader并将此批注附加到JUnit类:

@ContextConfiguration(loader=YourLoader.class)
Run Code Online (Sandbox Code Playgroud)

这是我的示例Loader,它实例化另一个或自定义ApplicationContext,而后者又可以使用自定义BeanFactory初始化(取决于功能):

public class XmlWebApplicationContextLoader extends AbstractContextLoader {

    public final ConfigurableApplicationContext loadContext(final String... locations) throws Exception {
        ServletContext servletContext = new MockServletContext("war", new FileSystemResourceLoader());
        GenericWebApplicationContext webContext = new GenericWebApplicationContext();
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
        webContext.setServletContext(servletContext);
        new XmlBeanDefinitionReader(webContext).loadBeanDefinitions(locations);        
        AnnotationConfigUtils.registerAnnotationConfigProcessors(webContext);
        webContext.refresh();
        webContext.registerShutdownHook();
        return webContext;
    }

    protected String getResourceSuffix() {
        return "";
    }
Run Code Online (Sandbox Code Playgroud)

}

在上面的例子中,应用程序上下文(由Spring Framework提供)具有构造函数:

public GenericWebApplicationContext(DefaultListableBeanFactory beanFactory) {
    super(beanFactory);
}
Run Code Online (Sandbox Code Playgroud)