Java 跨不同的Spock测试重用Spring应用程序上下文
我希望在Spock框架中编写的几个集成测试中重用相同的Spring上下文。 根据上下文,缓存基于Java 跨不同的Spock测试重用Spring应用程序上下文,java,spring,testing,integration-testing,spock,Java,Spring,Testing,Integration Testing,Spock,我希望在Spock框架中编写的几个集成测试中重用相同的Spring上下文。 根据上下文,缓存基于@ContextConfiguration注释的类属性 这是一个示例测试: @SpringBootTest @ContextConfiguration(classes = Application.class) class ExampleIntegrationTest extends Specification { def 'should reuse Spring context if alr
@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上下文。我想在不同的测试之间缓存它。
我错过什么了吗?基本上,我希望实现与这里描述的相同的功能,但是使用Spock而不是JUnit。上下文缓存是由Spring框架完成的,它遵循所描述的规则,即,它在不同的因素中构建上下文缓存键分解。只要它们都相同,它就会重用相同的上下文
- 位置(来自@ContextConfiguration)
- 类(来自@ContextConfiguration)
- ContextInitializerClass(来自@ContextConfiguration)
- ContextCustomizer(来自ContextCustomizerFactory)
- contextLoader(来自@ContextConfiguration)
- 父级(来自@ContextHierarchy)
- activeProfiles(来自@activeProfiles)
- propertySourceLocations(来自@TestPropertySource)
- propertySourceProperties(来自@TestPropertySource)
- resourceBasePath(来自@WebAppConfiguration)
Spock直接支持
@SpringBootTest
或任何其他Spring Boot测试注释,如@WebMvcTest
,您不应添加显式@ContextConfiguration(classes=Application.class)
上下文缓存由Spring框架完成,它遵循所述规则,即。,它在不同的因子中构建上下文缓存密钥因子。只要它们都相同,它就会重用相同的上下文
- 位置(来自@ContextConfiguration)
- 类(来自@ContextConfiguration)
- ContextInitializerClass(来自@ContextConfiguration)
- ContextCustomizer(来自ContextCustomizerFactory)
- contextLoader(来自@ContextConfiguration)
- 父级(来自@ContextHierarchy)
- activeProfiles(来自@activeProfiles)
- propertySourceLocations(来自@TestPropertySource)
- propertySourceProperties(来自@TestPropertySource)
- resourceBasePath(来自@WebAppConfiguration)
Spock直接支持
@SpringBootTest
或任何其他SpringBootTest注释,例如@WebMvcTest
,您不应该添加显式@ContextConfiguration(classes=Application.class)
谢谢您的回答。最后,结果是测试使用不同的配置文件运行,这就是为什么Spring没有重用上下文。k13i很好,您发现了差异,请接受答案。我的测试没有共享上下文,即使它们共享用@SpringBootTest注释的公共基类(webEnvironment=RANDOM_PORT,classes=[MyTestConfig,MyApp])
。上面列出的注释根本不使用。如何排除上下文缓存的故障?通过将记录器org.springframework.test.context.cache
设置为DEBUG
,您可以看到发生了什么。如果您使用的是@MockBean
,那么这也会阻止重用。感谢您的回答。最后它变成了o但是测试是用不同的配置文件运行的,这就是为什么Spring没有重用上下文。k13i很好,您发现了差异,请接受答案。我的测试没有共享上下文,即使它们共享一个用@springbootest注释的公共基类(webEnvironment=RANDOM\u PORT,classes=[MyTestConfig,MyApp])
。上面列出的注释根本不使用。如何排除上下文缓存故障?通过将记录器org.springframework.test.context.cache
设置为DEBUG
,您可以看到发生了什么。如果您使用的是@MockBean
,那么这也会阻止重用。