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")

相关文章