java - 如何很好地对异步方法进行单元测试?

标签 java unit-testing asynchronous junit

我目前正在使用线程锁定对我的异步方法进行单元测试,通常我会注入(inject)一个 CountDownLatch进入我的异步组件并让主线程等待它达到 0。但是,这种方法看起来很丑陋,而且扩展性不好,考虑一下当我为一个组件编写 100 多个测试并且它们都依次具有时会发生什么等待工作线程执行一些伪造的异步作业。

那么还有别的方法吗?考虑以下简单搜索机制的示例:

搜索器.java

public class Searcher {

    private SearcherListener listener;

    public void search(String input) {
        // Dispatch request to queue and notify listener when finished
    }

}

SearcherListener.java

public interface SearcherListener {

    public void searchFinished(String[] results);

}

如何在不使用多个线程并阻塞一个线程等待另一个线程的情况下对 search 方法进行单元测试?我的灵感来自 How to use Junit to test asynchronous processes但最重要的答案没有提供具体的解决方案。

最佳答案

另一种方法:

只是不要启动线程。就这样。 假设您有一个使用 Searcher 类的 SearcherService。 然后不要启动异步 SearcherService,而只是调用 searcher.search(),它会阻塞直到搜索完成。

Searcher s = new Searcher();
s.search(); // blocks and returns when finished
// now somehow check the result

关于java - 如何很好地对异步方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21946851/

相关文章:

wpf - 如何覆盖 WPF 中的 TreeViewItem 以允许异步加载子项?

java - jdbc 瘦驱动程序中的机器名称而不是 ipaddress

java - 持久性错误

java - parent 的 onAreaTouched 会触发 child 的吗?

java - 如何在不运行整个作业的情况下测试 Spring Batch 步骤

javascript - 为什么React setState可以异步?

c# - 在 C# 中如何在同一线程中运行异步方法

java - StringIndexOutOfBoundsException 字符串索引超出范围 : 0

python - 是否可以测试使用 `os._exit()` 的函数?

iOS 单元测试实例变量