@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
注意:我知道,我可以通过一些可测试的方式更改方法。在这种情况下,我不能这样做。
有什么办法可以模拟这本书的缓存吗?