gpt4 book ai didi

java - 在 Spring Boot 测试中测试 @Cacheable : Caffeine cache not invoked on MockBean

转载 作者:行者123 更新时间:2023-11-30 01:55:48 27 4
gpt4 key购买 nike

我想测试由 @Cacheable 注释缓存的服务级别方法。我正在使用 Mockito mock 该服务。以下是我的缓存配置和实际测试

缓存尚未使用,Mockito 验证失败,方法被调用两次(而不是一次)

我的缓存配置:

@Configuration
@EnableCaching
public class CacheConfiguration implements CachingConfigurer {

private static final Log LOG = LogFactory.getLog(CacheConfiguration.class);

@Override
@Bean
public CaffeineCacheManager cacheManager() {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(
"sample-cache");
caffeineCacheManager.setCaffeine(caffeineCacheBuilder());
caffeineCacheManager.setAllowNullValues(false);
return caffeineCacheManager;
}

Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder().maximumSize(50)
.expireAfterAccess(30, TimeUnit.MINUTES).softValues();
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = *Application.class)
@AutoConfigureMockMvc
public class CachingIntegrationTest {

@MockBean
private Service service;

@Before
public void setUp() throws {

Mockito.reset(service);
String eg = "eg"''

Mockito.when(service.serviceMethod(argument))
.thenReturn(eg);

}

@Test
public void verifyCache() throws {

service.serviceMethod(argument);

service.serviceMethod(argument);
Mockito.verify(service, Mockito.times(1)).serviceMethod(argument);

}

最佳答案

我不确定,但如果 @Cacheable 注释仍然有效,即使实际上没有使用带注释的对象,而是使用它的 Mockito 模拟,我会感到惊讶。原因是这两种技术(即面向方面的编程注释 @Cacheable 和模拟)都是通过 Java 动态代理(或等效的字节码生成)实现的,因此它们很可能会互相妨碍。

您应该做的是模拟您的服务的协作者,然后检查这些协作者的调用次数。

关于java - 在 Spring Boot 测试中测试 @Cacheable : Caffeine cache not invoked on MockBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54559606/

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