java - Guava 加载缓存 : How to unit test ListenableFuture within CacheLoader

标签 java unit-testing junit mockito guava

我正在使用Guava LoadingCache像这样:

@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
    // ...
}

我可以测试除一行之外的每一行。如何在 Runnable 任务中对 return loadResource(cacheKey) 行进行单元测试?现在我正在模拟 executorService 以确保异步刷新确实发生。

最佳答案

您可以使用sameThreadExecutor,而不是模拟ExecutorService所以任务会立即执行。

关于java - Guava 加载缓存 : How to unit test ListenableFuture within CacheLoader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24307737/

相关文章:

java - 朝向 JAVA_HOME 的 "true"定义

c++ - 单元测试私有(private)方法是一种好习惯吗?

java - 使用 H2 db 模拟 Jdbctemplate 会出现错误

java - 私有(private)成员(member)无法访问?

java - 当 Id 由数据库设置时,使用 Mockito 测试服务

java - 按时间对来自 2 个或更多不同来源的帖子进行排序

java - Hibernate 进行不必要的子查询来获取数据

java - 如何停止重绘()闪烁

unit-testing - 在同一JUnit测试中同时使用Arquillian和PowerMock

unit-testing - Xcode 6.3 缺少单元测试状态/在编辑器中运行