【发布时间】:2021-08-22 11:40:09
【问题描述】:
我正在尝试使用以下代码测试 @Cacheable 方法,但它不起作用,该方法没有被缓存,如果我没有将 @Cacheable 放在 getCountCache 方法中,而是将它放在 getCount 方法中进行测试工作,尝试了很多东西,但找不到原因。
@ContextConfiguration
@ExtendWith(SpringExtension.class)
public class CacheTest {
static class MyRepoImpl {
private Count count;
public MyRepoImpl(Count count){
this.count = count;
}
public int getCount(String key){
return getCountCache(key);
}
@Cacheable(cacheNames = "sample")
public int getCountCache(String key) {
return count.getCount();
}
}
static class Count {
int i = 0;
public int getCount() {
return i++;
}
}
@EnableCaching
@Configuration
public static class Config {
@Bean CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
@Bean MyRepoImpl myRepo() {
count = Mockito.mock(Count.class);
return new MyRepoImpl(count);
}
}
static Count count;
@Autowired MyRepoImpl repo;
@Test
public void methodInvocationShouldBeCached() {
Mockito.when(count.getCount()).thenReturn(1, 2, 3, 4);
Object result = repo.getCount("foo");
assertThat(result).isEqualTo(1);
Mockito.verify(count, Mockito.times(1)).getCount();
result = repo.getCount("foo");
assertThat(result).isEqualTo(1);
Mockito.verify(count, Mockito.times(1)).getCount();
}
}
【问题讨论】:
标签: spring testing mockito spring-cache