我正在努力提高我正在从事的一个项目的Spring集成测试的性能。我们使用Spring + Gradle + JUnit。
在build.gradle
文件中使用此配置:
test {
useJUnit()
setForkEvery(0)
setMaxParallelForks(1)
}
我们能够在一个JVM中运行所有测试。虽然我认为这是默认行为。
但是我一直在阅读关于Spring测试上下文缓存的文章,并且在我的应用程序中使用了这个属性-test.yml:
logging:
level:
org:
springframework:
test:
context:
cache: DEBUG
我注意到在同一个类中运行的测试方法的下列日志
2017-09-05 08:33:11.829 DEBUG 5764 --- [ Test worker] c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [THIS HAD SENSITIVE DATA]
2017-09-05 08:33:11.830 DEBUG 5764 --- [ Test worker] org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@572e81e7 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
2017-09-05 08:33:11.849 DEBUG 5764 --- [ Test worker] c.DefaultCacheAwareContextLoaderDelegate : Retrieved ApplicationContext from cache with key [THIS HAD SENSITIVE DATA]
2017-09-05 08:33:11.850 DEBUG 5764 --- [ Test worker] org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@572e81e7 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 1]
还有更多的行表示Retrieved ApplicationContext from cache with key...
。
对于在其他类中运行的测试方法,我注意到类似的日志,例如:
2017-09-05 08:33:12.971 DEBUG 10288 --- [ Test worker] c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [THIS HAD SENSITIVE DATA]
2017-09-05 08:33:12.971 DEBUG 10288 --- [ Test worker] org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@2dad6721 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
2017-09-05 08:33:13.194 DEBUG 10288 --- [ Test worker] c.DefaultCacheAwareContextLoaderDelegate : Retrieved ApplicationContext from cache with key [THIS HAD SENSITIVE DATA]
2017-09-05 08:33:13.194 DEBUG 10288 --- [ Test worker] org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@2dad6721 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 1]
这两个类都有相同的注释:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles({"default", "profile-1", "profile-2"})
public class SomeControllerTest {
// Test methods...
}
我认为两个类中的测试方法应该能够共享相同的ApplicationContext
,从而减少测试持续的时间。但是,有可能做到这一点吗?如果是这样的话,是怎么做的?
我注意到两个ApplicationContext
对象大约同时存储在缓存中,08:33:11.829
和08:33:12.971
。测试运行程序在不同的线程中执行测试吗?
发布于 2017-09-06 06:04:00
您的上下文实际上是缓存的,但是由于使用Spring的@MockBean
特性,您实际上有两个不同的上下文。
@MockBean
的使用使每个ApplicationContext
都有一个不同的唯一键,将其存储在上下文缓存中。
尽管在任何地方都可能没有公开文档,但实际上在org.springframework.boot.test.mock.mockito.MockitoContextCustomizerFactory
的实现中有在线文档。
我们在这里收集显式模拟定义,因为它们构成了MergedContextConfiguration键的一部分。不同的模拟需要有不同的键。
我已经打开了一个针对Spring的问题来记录这个行为:https://github.com/spring-projects/spring-boot/issues/10182
https://stackoverflow.com/questions/46060579
复制相似问题