故障排除 Spring TestContext 缓存

Troubleshooting Spring TestContext caching

Spring TestContext Framework 根据几个键缓存上下文。

如何记录缓存键以确保我的测试重用上下文?

如 Spring 参考手册的 Context Caching 部分所述...

Since having a large number of application contexts loaded within a given test suite can cause the suite to take an unnecessarily long time to execute, it is often beneficial to know exactly how many contexts have been loaded and cached. To view the statistics for the underlying context cache, you can set the log level for the org.springframework.test.context.cache logging category to DEBUG.

除了支持 Sam 的回答之外,如果在 org.springframework.test.context.cache 上启用 DEBUG 级别,您还可以看到:

DEBUG org.springframework.test.context.BootstrapUtils
  Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]

DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate
  Storing ApplicationContext in cache under key
  [[MergedContextConfiguration testClass = XTest,
    locations = '{}',
    classes = '{...}',
    contextInitializerClasses = '[...]',
    activeProfiles = '{}',
    propertySourceLocations = '{classpath:application-test.properties}',
    propertySourceProperties = '{...}', contextCustomizers = set[...],
    contextLoader = 'org.springframework.test.context.support.AnnotationConfigContextLoader',
    parent = [null]]]

DEBUG org.springframework.test.context.cache
  Spring test ApplicationContext cache statistics:
  [DefaultContextCache@6ef2f7ad size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]

DEBUG org.springframework.test.context.cache
  Spring test ApplicationContext cache statistics:
  [DefaultContextCache@6ef2f7ad size = 1, maxSize = 32, parentContextCount = 0, hitCount = 6, missCount = 1]

很难读取缓存键详细信息,但以下缓存统计信息不言而喻。