【问题标题】:Reuse Spring application context across different Spock tests在不同的 Spock 测试中重用 Spring 应用程序上下文
【发布时间】:2019-04-10 14:06:19
【问题描述】:

我想在用 Spock 框架编写的多个集成测试中重用相同的 Spring 上下文。 根据documentation 上下文缓存是基于@ContextConfiguration 注释的classes 属性。

这是一个示例测试:

@SpringBootTest
@ContextConfiguration(classes = Application.class)
class ExampleIntegrationTest extends Specification {

    def 'should reuse Spring context if already created'() {
        expect:
        1 == 1
    }
}

第二个测试也包含相同的@ContextConfiguration注解,即

@ContextConfiguration(classes = Application.class)

但是当我运行所有测试时,我可以在控制台中看到每个测试都会创建 Spring 上下文。我想在不同的测试之间缓存它。 我错过了什么吗?基本上,我想实现与此处(stackoverflow question) 中描述的相同的事情,但使用 Spock 而不是 JUnit。

【问题讨论】:

    标签: java spring testing integration-testing spock


    【解决方案1】:

    上下文缓存是由 Spring 框架完成的,它遵循here 中描述的规则,即,它构建了一个上下文缓存键,考虑了不同的因素。只要它们都相同,它就会重用相同的上下文。

    • 位置(来自@ContextConfiguration)
    • 类(来自@ContextConfiguration)
    • contextInitializerClasses(来自@ContextConfiguration)
    • contextCustomizers(来自 ContextCustomizerFactory)
    • contextLoader(来自@ContextConfiguration)
    • 父级(来自@ContextHierarchy)
    • activeProfiles(来自@ActiveProfiles)
    • propertySourceLocations(来自@TestPropertySource)
    • propertySourceProperties(来自@TestPropertySource)
    • resourceBasePath(来自@WebAppConfiguration)

    Spock 直接支持 @SpringBootTest 或任何其他 Spring Boot 测试注释,例如 @WebMvcTest,您不应添加显式 @ContextConfiguration(classes = Application.class)

    【讨论】:

    • 感谢您的回答。最后发现测试使用不同的配置文件运行,这就是 Spring 不重用上下文的原因。
    • k13i 很好,你发现了不同之处,请你接受答案。
    • 我的测试没有共享上下文,即使它们共享一个用@SpringBootTest(webEnvironment = RANDOM_PORT, classes = [MyTestConfig, MyApp]) 注释的公共基类。上面列出的注释根本没有使用。如何解决上下文缓存问题?
    • 您可以通过将记录器org.springframework.test.context.cache 设置为DEBUG 来查看发生了什么。如果您使用的是@MockBean,那么这也会阻止重复使用。
    猜你喜欢
    • 2018-01-20
    • 2018-08-27
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2012-10-28
    相关资源
    最近更新 更多