Reputation: 1
I'm using the Guava LoadingCache like this:
@Inject
private ExecutorService executorService;
private LoadingCache<CacheKey, ResponseEntity<String>> constructCache() {
return CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(15, TimeUnit.MINUTES)
.build(
new CacheLoader<CacheKey, ResponseEntity<String>>() {
@Override
public ResponseEntity<String> load(CacheKey cacheKey) throws Exception {
return loadResource(cacheKey);
}
@Override
public ListenableFuture<ResponseEntity<String>> reload(final CacheKey cacheKey, ResponseEntity<String> old) {
ListenableFutureTask<ResponseEntity<String>> task = ListenableFutureTask.create(new Callable<ResponseEntity<String>>() {
@Override
public ResponseEntity<String> call() throws Exception {
// this line here!
return loadResource(cacheKey);
}
});
executorService.execute(task);
return task;
}
}
);
}
private ResponseEntity<String> loadResource(CacheKey cacheKey) {
// ...
// external call
// ...
}
I can test every line except one. How do I unit test the line return loadResource(cacheKey)
within the Runnable task? Right now I'm mocking the executorService in order to make sure the asynchronous refresh is really taking place.
Upvotes: 0
Views: 2979
Reputation: 11725
Instead of mocking the ExecutorService
, you can use the sameThreadExecutor
so the task is immediately executed.
Upvotes: 2
Reputation: 32969
If you are mocking the ExecutorService
, use an ArgumentCaptor
to get the ListenableFutureTask
that was passed. Execute the call
method on the task and verify that loadResource
was called.
Upvotes: 0