如何模拟Google Guava缓存构建器?

时间:2017-01-10 12:15:39

标签: java unit-testing mocking mockito google-guava-cache

    @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缓存。

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异常。

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

注意:我知道,我可以通过一些可测试的方式更改方法。在这种情况下,我无法做到。

有没有办法模拟这本书的缓存?

1 个答案:

答案 0 :(得分:2)

如果你最好嘲笑get方法调用,那么你的代码应该可以工作,以确保参数匹配,这样你就可以得到预期的书籍实例。

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);
        ...
    }
}