基于Spring Boot的测试中的上下文层次结构
我的Spring Boot" title="Spring Boot">Spring Boot应用程序是这样启动的:
new SpringApplicationBuilder()  .sources(ParentCtxConfig.class)
  .child(ChildFirstCtxConfig.class)
  .sibling(ChildSecondCtxConfig.class)
  .run(args);
Config类用注释@SpringBootApplication。结果,我有一个根上下文和两个子Web上下文。
我想编写集成测试,并且希望在那里具有相同的上下文层次结构。我至少要ChildFirstCtxConfig.class使用其父上下文(ParentCtxConfig.class)测试第一个子上下文(已配置)。我该如何实现?
目前,我已ApplicationContext在测试中自动接线,因此可以对其进行检查。我在测试中有此类注释:
@RunWith(SpringRunner.class)    @SpringBootTest(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
但这将产生单个上下文,我想要父子层次结构。我假设我应该用注解对测试进行@ContextHierarchy注解。
将我的测试注释更改为此似乎与之前的示例完全相同:
@RunWith(SpringRunner.class)    @ContextConfiguration(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
但是,如果我要介绍@ContextHierarchy并具有以下内容:
@RunWith(SpringRunner.class)@ContextHierarchy({
        @ContextConfiguration(name = "root", classes = ParentCtxConfig.class),
        @ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class)
})
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
上下文未启动,因为无法在子上下文中找到/自动装配在父上下文中定义的bean。设置loader =
SpringBootContextLoader.class没有帮助。
示例代码:GitHub
回答:
如Peter Davis所述,此问题已在Spring Boot 1.5.0中修复。
这是的限制@SpringBootTest。准确移动,这是的限制SpringBootContextLoader。您可以通过使用配置父上下文的自定义上下文加载器或ContextCustomizer需要在中列出的工厂来解决此问题spring.factories。这是后者的粗略示例:
src / test / resources / META-INF / spring.factories:
org.springframework.test.context.ContextCustomizerFactory=\com.alex.demo.ctx.HierarchyContextCustomizerFactory
src / test / java / com / alex / demo / ctx /
HierarchyContextCustomizerFactory.java:
package com.alex.demo.ctx;import java.util.List;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.MergedContextConfiguration;
public class HierarchyContextCustomizerFactory implements ContextCustomizerFactory {
    @Override
    public ContextCustomizer createContextCustomizer(Class<?> testClass,
            List<ContextConfigurationAttributes> configAttributes) {
        return new ContextCustomizer() {
            @Override
            public void customizeContext(ConfigurableApplicationContext context,
                    MergedContextConfiguration mergedConfig) {
                if (mergedConfig.getParentApplicationContext() != null) {
                    context.setParent(mergedConfig.getParentApplicationContext());
                }
            }
        };
    }
}
以上是 基于Spring Boot的测试中的上下文层次结构 的全部内容, 来源链接: utcz.com/qa/422686.html








