2
    @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

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

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

4

1 回答 1

2

如果您更好地将get方法调用模拟为 next 以确保参数匹配,您的代码应该可以工作,这样您将获得预期的 book 实例作为结果。

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);
        ...
    }
}
于 2017-01-10T12:39:54.720 回答