Spring 声明式缓存测试仅在测试直接调用 @Cacheable 方法时有效

Spring declarative caching test only works if testing direct call to @Cacheable method

我正在尝试使用以下代码测试 @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 缓存在代理上工作,从 class 内部调用的用 @Cachable 注释的 bean 方法将不会缓存。您需要直接从 class 外部调用它以使缓存机制起作用。 Spring cache @Cacheable method ignored when called from within the same class这个解释真好