Spring Boot 2 - Testing @Cacheable with Mockito for method without arguments is not working(Spring Boot 2-使用Mockito为不带参数的方法测试@cacheable不起作用)
问题描述
我有一个使用Spring Boot 2的应用程序。我想测试一个带有@cacheable(Spring Cache)的方法。我举了一个简单的例子来说明我的想法:
@Service
public class KeyService {
@Cacheable("keyCache")
public String getKey() {
return "fakeKey";
}
}
和测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class KeyServiceTest {
@Autowired
private KeyService keyService;
@Test
public void shouldReturnTheSameKey() {
Mockito.when(keyService.getKey()).thenReturn("key1", "key2");
String firstCall = keyService.getKey();
assertEquals("key1", firstCall);
String secondCall = keyService.getKey();
assertEquals("key1", secondCall);
}
@EnableCaching
@Configuration
static class KeyServiceConfig {
@Bean
KeyService keyService() {
return Mockito.mock(KeyService.class);
}
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager("keyCache");
}
}
}
上面的示例不起作用。但是,如果我更改getKey()方法以接收参数:
@Service
public class KeyService {
@Cacheable("keyCache")
public String getKey(String param) {
return "fakeKey";
}
}
并重构测试以适应该更改,测试即可成功运行:
@RunWith(SpringRunner.class)
@SpringBootTest
public class KeyServiceTest {
@Autowired
private KeyService keyService;
@Test
public void shouldReturnTheSameKey() {
Mockito.when(keyService.getKey(Mockito.anyString())).thenReturn("key1", "key2");
String firstCall = keyService.getKey("xyz");
assertEquals("key1", firstCall);
String secondCall = keyService.getKey("xyz");
assertEquals("key1", secondCall);
}
@EnableCaching
@Configuration
static class KeyServiceConfig { //The same code as shown above }
}
你们对这个问题有什么想法吗?
推荐答案
使用方法参数作为键执行缓存查找。这意味着您需要没有参数的方法的密钥。尝试此@Cacheable(value = "keyCache", key = "#root.methodName")
这篇关于Spring Boot 2-使用Mockito为不带参数的方法测试@cacheable不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring Boot 2-使用Mockito为不带参数的方法测试@cacheable不起作用
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
