如何模拟谷歌番石榴缓存生成器? [英] How to mock Google Guava cache builder?

查看:128
本文介绍了如何模拟谷歌番石榴缓存生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    @Component
    public class LibraryService {

        @Autowired
        private BookService bookService;

        private Cache<UUID, Book> bookCache = CacheBuilder.newBuilder().maximumSize(512).expireAfterWrite(15, TimeUnit.MINUTES).build();

        public void someMethod(UUID bookId) {
          try {
            Book book = bookCache.get(bookId, () -> bookService.findBookByUuid(bookId));
            //some operations
          } catch (ExecutionException e) {
            throw new ProcessingFailureException("Failed to load cache value", e);
          }

         }

    }

我需要为此类编写单元测试,以便尝试按以下方式模拟Google Guava缓存.

I need to write unit test for this class so that I tried to mock the Google Guava cache as following.

public class LibraryServiceTest {

    @InjectMocks
    private LibraryService service;

    @Mock
    private BookService bookService;

    @Mock
    private Cache<UUID, Book> bookCache;

    @Before
    public void initialize() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testMethod() throws ExecutionException {
        UUID bookId = UUID.randomUUID();
        Book book = new Book();

        when(bookCache.get(bookId, () -> bookService.findBookByUuid(bookId))).thenReturn(book);

        service.someMethod(bookId);
    }
}

我遇到了NullPointer异常.

I got some NullPointer Exception.

com.google.common.util.concurrent.UncheckedExecutionException: java.lang.NullPointerException
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2203)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
    at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4739)
Caused by: java.lang.NullPointerException

注意:我知道,我可以以某种可测试的方式更改此方法.在这种情况下,我无法做到这一点.

Note: I know, I can change the method some testable way. In this case I couldn't do that.

有什么方法可以模拟这本书的缓存?

Is there any way to mock this book cache?

推荐答案

如果您更好地模拟了接下来的get方法调用以确保参数匹配,则您的代码应该可以工作,以确保获得所需的书籍实例作为结果. /p>

Your code should work if you better mock the get method call as next to ensure arguments match such that you will get the expected book instance as result.

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
...

public class LibraryServiceTest {
    ...

    @Test
    public void testMethod() throws ExecutionException {
        ...
        when(bookCache.get(eq(bookId), any(Callable.class))).thenReturn(book);
        ...
    }
}

这篇关于如何模拟谷歌番石榴缓存生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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