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

时间:2019-04-10 14:06:19

标签: java spring testing integration-testing spock

我想在以Spock框架编写的多个集成测试中重用相同的Spring上下文。 根据{{​​3}},上下文缓存基于classes批注的@ContextConfiguration属性。

这是一个示例测试:

@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上下文。我想在不同的测试之间缓存它。 我想念什么吗?基本上,我想实现与此处documentation相同的内容,但是要使用Spock而不是JUnit。

1 个答案:

答案 0 :(得分: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)

相关问题