I'm trying to test a @Cacheable method using the following code, but is not working, the method is not being cached, if instead of putting the @Cacheable in the getCountCache method I put it in the getCount method the test works, tried a lot of things but couldn't find the cause.
@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();
}
}