单个测试执行问题期间的多个 spring 上下文

Multiple spring context during single test execution problem

我有接口和 2 个实现,它们是根据 属性 值实例化的。

    @Bean
    @ConditionalOnProperty(value = "stitching", havingValue = "false", matchIfMissing = true)
    public LastEventProvider noStitchingLastEventProvider() {
        return new NoStitchingLastEventProvider();
    }
    @Bean
    @ConditionalOnProperty(value = "stitching", havingValue = "true")
    public LastEventProvider withStitchingLastEventProvider() {
            return new WithStitchingLastEventProvider();
    }

有测试类使用stitching=true,有类使用stitching=false 当我运行单独测试类时,没有问题。当我运行所有测试类时,一个测试方法失败。在失败测试的日志中,我看到了非常奇怪的行为: 根据我的日志,在测试开始时,我看到测试方法使用了第二个实例,而在测试结束时它使用了第一个!!!

context: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2e1e02b8, started on Tue Feb 16 14:12:00 IST 2021, parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@237cd4e5
14:12:30.256 [test-map-updater-status--test-0-C-1] TRACE c.m.m.s.a.WithStitchingLastEventProvider bla-bla
.
.
context: springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@348d18a3, started on Tue Feb 16 14:09:51 IST 2021, parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@7da10b5b
14:12:33.212 [test-map-updater-status--test-0-C-1] TRACE c.m.m.s.a.NoStitchingLastEventProvider - a-bla

我在使用 LastEventProvider 之前记录了 applicationContext 对象,发现在测试期间有 2 个不同的应用程序上下文!! 这是我使用 spring 12 年来看到的最奇怪的问题。 有任何想法吗? Spring 引导版本为 2.2.2.RELEASE。非常感谢!

我没有解决问题,但我实施了解决方法:我用 junit5 @Tag 注释(@Tag("withStitching") 和 @Tag("noStitching"))标记了所有测试 类 ,在我的构建中创建了 2 个 Maven 配置文件和 运行 测试作为单独的步骤。