java - 一般如何测试非 RxJava 可观察对象或异步代码?

标签 java unit-testing testing asynchronous reactive-programming

我正在尝试实现我自己的 observables 或从其他语言移植它们以获得乐趣和利润。

我遇到的问题是,关于如何正确测试可观察对象或一般异步代码的信息非常少。

考虑以下测试代码:

// Create a stream of values emitted every 100 milliseconds
// `interval` uses Timer internally
final Stream<Number> stream = 
  Streams.interval(100).map(number -> number.intValue() * 10);

ArrayList<Number> expected = new ArrayList<>();

expected.add(0);
expected.add(10);
expected.add(20);

IObserver<Number> observer = new IObserver<Number>() {
  public void next(Number x) {
    assertEquals(x, expected.get(0));
    expected.remove(0);
    if(expected.size() == 0) {
      stream.unsubscribe(this);
    }
  }
  public void error(Exception e) {}
  public void complete() {}
};

stream.subscribe(observer);

一旦流被订阅,它就会发出第一个值。 onNext 被调用...然后测试成功退出。

在 JavaScript 中,如今大多数测试框架都为测试用例提供了一个可选的 Promise,您可以在成功/失败时异步调用它。 Java 有类似的东西吗?

最佳答案

由于执行是异步的,您必须等到完成。你可以用老式的方式等待一段时间

 your_code
 wait(1000)
 check results.

或者,如果您使用 Observables,您可以使用 TestSubscriber 在此示例中,您可以看到我们如何进行异步操作,直到观察者消耗完所有项目。

@Test
public void testObservableAsync() throws InterruptedException {
    Subscription subscription = Observable.from(numbers)
            .doOnNext(increaseTotalItemsEmitted())
            .subscribeOn(Schedulers.newThread())
            .subscribe(number -> System.out.println("Items emitted:" + total));
    System.out.println("I finish before the observable finish.  Items emitted:" + total);


    new TestSubscriber((Observer) subscription)
            .awaitTerminalEvent(100, TimeUnit.MILLISECONDS);
}

您可以在此处查看更多异步示例 https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/scheduler/ObservableAsynchronous.java

关于java - 一般如何测试非 RxJava 可观察对象或异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39012809/

相关文章:

java - 检查java中是否存在char

java - XPath 从多个节点获取文本

java - 新的 JUnit 4.8.1 @Category 渲染测试套件是否几乎过时了?

iphone - 如何更改 iOS Kif 测试的顺序?

java - 获取 java.sql.SQLException:JAVA 中 CallableStatement 上的索引::4 处缺少 IN 或 OUT 参数

java - 无法使 Google Cloud Message 保持 Activity 状态

c# - 使用 Nunit 3.x 的参数化测试

c# - 如何对该方法进行单元测试

python - 按名称重用 python 中的方法

c++ - 如何为我的 Qt UDP 程序模拟数据包丢失?