Java JUnit 5缓存管理器初始化数据测试-空缓存管理器
我曾在SpringBoot1.x和JUnit4中使用过这个功能,但在切换到SpringBoot2.x和JUnit5之后,它就不再工作了 使用Caffine作为我们的缓存管理器 测试的目的是确保我们的缓存使用一些常量进行预加载,这并不复杂Java JUnit 5缓存管理器初始化数据测试-空缓存管理器,java,spring-boot,caching,junit,spring-cache,Java,Spring Boot,Caching,Junit,Spring Cache,我曾在SpringBoot1.x和JUnit4中使用过这个功能,但在切换到SpringBoot2.x和JUnit5之后,它就不再工作了 使用Caffine作为我们的缓存管理器 测试的目的是确保我们的缓存使用一些常量进行预加载,这并不复杂 @ContextConfiguration(classes = CacheConfig.class) @EnableConfigurationProperties public class CacheConfigTest { @Autowired
@ContextConfiguration(classes = CacheConfig.class)
@EnableConfigurationProperties
public class CacheConfigTest {
@Autowired
private CacheManager myCacheManager;
@Test
public void verifyCacheManagerIsInitializedWithCaches() {
CacheConstants.CACHES.forEach(cacheName -> {
assertTrue(myCacheManager.getCacheNames().contains(cacheName)));
}
}
}
当我现在运行它时,myCacheManager
为null,这导致代码的其余部分抛出null指针异常,这并不奇怪
下面是CacheConfig类供参考
@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
private static final String CACHE_EXPIRE_ONE_HOUR = "expireAfterAccess=3600s, expireAfterWrite=3600s";
@Bean
@Override
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager(CacheConstants.SOME_CONSTANT);
cacheManager.setCacheSpecification(CACHE_EXPIRE_ONE_HOUR);
return cacheManager;
}
@Bean
public CacheManager myCacheManager() {
return new CaffeineCacheManager(Arrays.stream(CacheConstants.CACHES.toArray()).toArray(String[]::new));
}
}
由于我从JUnit4->JUnit5开始,我不得不从所有测试类中删除@RunWith注释。太棒了,一切都很顺利 事实证明,我需要使用缓存将@ExtendWith注释添加到测试类的顶部
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CacheConfig.class)
@EnableConfigurationProperties
public class CacheConfigTest { ...
我不太清楚为什么仅仅在这些情况下就需要它,但它必须与缓存加载的方式有关。出于某种原因,spring不知道如何为它加载正确的上下文