【问题标题】:Spring declarative caching test only works if testing direct call to @Cacheable methodSpring 声明式缓存测试仅在测试对 @Cacheable 方法的直接调用时才有效
【发布时间】: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


    【解决方案1】:

    由于 Spring 缓存在代理上使用 @Cachable 注释的 bean 方法从类内部调用不会缓存。您需要直接从类外部调用它才能使缓存机制起作用。 Spring cache @Cacheable method ignored when called from within the same class这个解释真好。

    【讨论】:

    • 恭维 Maciej 的 答案,这是绝对正确的,并且鉴于 Spring 的缓存抽象 是基于 AOP(很像 Spring 的 Transaction Management & Transaction Demarcation),那么您可以在这里阅读更多关于 Proxy 为何如此行为的信息:docs.spring.io/spring-framework/docs/current/reference/html/…
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 2020-06-27
    • 2014-08-06
    • 2017-09-04
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多