Spring Boot 2-使用Mockito为不带参数的方法测试@cacheable不起作用 [英] Spring Boot 2 - Testing @Cacheable with Mockito for method without arguments is not working

查看:95
本文介绍了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不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆