gpt4 book ai didi

java - JUnit 5 缓存管理器初始化数据测试 - 空缓存管理器

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:24 25 4
gpt4 key购买 nike

我在 Spring Boot 1.x 和 JUnit 4 中使用了此功能,但在切换到 Spring Boot 2.x 和 JUnit 5 后,它不再工作。

使用 Caffine 作为我们的缓存管理器。

测试是为了确保我们的缓存正在预加载一些常量,没什么复杂的。

@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 为空,导致其余代码毫不奇怪地抛出空指针异常。

这里是 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));
}
}

最佳答案

自从我从 JUnit 4 -> JUnit 5 开始,我必须从所有测试类中删除 @RunWith 注释。这太棒了,一切都运行良好。

结果我需要使用缓存将 @ExtendWith 注释添加到测试类的顶部。

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CacheConfig.class)
@EnableConfigurationProperties
public class CacheConfigTest { ...

我不太确定为什么在这些情况下需要它,但它一定与缓存加载的方式有关。由于某种原因,spring 不知道如何在没有它的情况下为其加载正确的上下文

关于java - JUnit 5 缓存管理器初始化数据测试 - 空缓存管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57151202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com