简体   繁体   English

在不同的Spock测试中重用Spring应用程序上下文

[英]Reuse Spring application context across different Spock tests

I would like to reuse the same Spring context across several integration tests written in Spock framework. 我想在以Spock框架编写的多个集成测试中重用相同的Spring上下文。 According to the documentation context caching is based on classes property of @ContextConfiguration annotation. 根据文档,上下文缓存基于@ContextConfiguration批注的classes属性。

That's an example test: 这是一个示例测试:

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

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

The second test also contains the same @ContextConfiguration annotation, ie 第二个测试还包含相同的@ContextConfiguration批注,即

@ContextConfiguration(classes = Application.class)

but when I run all tests I can see in the console that Spring context is created per each test. 但是当我运行所有测试时,我可以在控制台中看到每个测试都会创建Spring上下文。 I would like to cache it between different tests. 我想在不同的测试之间缓存它。 Am I missing something? 我想念什么吗? Basically, I would like to achieve the same thing as described here (stackoverflow question) but in Spock instead of JUnit. 基本上,我想实现与此处所述相同的内容(stackoverflow问题),但使用Spock而不是JUnit。

Context Caching is done by the Spring Framework, it follows the rules described here , ie, it builds a context cache key factoring in different factors. 上下文缓存由Spring框架完成,它遵循此处描述的规则,即,它在不同因素下构建了上下文缓存键因子。 As long as all of them are the same, it reuses the same context. 只要它们都相同,它就会重用相同的上下文。

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

Spock supports @SpringBootTest or any of the other Spring Boot test annotations, such as @WebMvcTest , directly and you should not add an explicit @ContextConfiguration(classes = Application.class) . Spock直接支持@SpringBootTest或其他任何Spring Boot测试注释,例如@WebMvcTest ,并且您不应添加显式的@ContextConfiguration(classes = Application.class)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM