【问题标题】:Spring Boot 2 - Testing @Cacheable with Mockito for method without arguments is not workingSpring Boot 2 - 使用 Mockito 测试 @Cacheable 以获取没有参数的方法不起作用
【发布时间】:2018-11-04 06:50:15
【问题描述】:

我有一个使用 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 }
}

你们对这个问题有什么想法吗?

【问题讨论】:

  • 你找到解决问题了吗@vallim 我试过@Cacheable(value = "keyCache", key = "#root.methodName"),它给出的建议似乎不起作用

标签: java spring spring-boot mockito spring-cache


【解决方案1】:

我想知道您是否遇到了默认密钥生成策略的问题:spring documentation。这似乎是两者最大的区别。它正在改变它用于密钥的内容,尽管我认为两者都应该工作。

【讨论】:

    【解决方案2】:

    使用方法参数作为键执行缓存查找。这意味着您需要一个没有参数的方法的密钥。试试这个@Cacheable(value = "keyCache", key = "#root.methodName")

    【讨论】:

    • 我试过你的解决方案,还是不行?有什么建议? @Bizon4ik
    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 2017-05-22
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2018-12-23
    • 2020-01-20
    相关资源
    最近更新 更多