Context hierarchy in Spring Boot based tests

前端 未结 1 543
鱼传尺愫
鱼传尺愫 2021-02-09 00:07

My Spring Boot application is started like this:

new SpringApplicationBuilder()
  .sources(ParentCtxConfig.class)
  .child(ChildFirstCtxConfig.class)
  .sibling(         


        
1条回答
  •  日久生厌
    2021-02-09 00:35

    Update: This issue was fixed in Spring Boot 1.5.0 as mentioned by Peter Davis.

    This is a limitation of @SpringBootTest. Move accurately, it's a limitation of SpringBootContextLoader. You could work around it by using a custom context loader that configures the parent context or with a ContextCustomizer the factory for which would need to be listed in spring.factories. Here's a rough example of the latter:

    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 configAttributes) {
            return new ContextCustomizer() {
    
                @Override
                public void customizeContext(ConfigurableApplicationContext context,
                        MergedContextConfiguration mergedConfig) {
                    if (mergedConfig.getParentApplicationContext() != null) {
                        context.setParent(mergedConfig.getParentApplicationContext());
                    }
    
                }
    
            };
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题