java - RxJava - 测试 Single.zip() 以确保执行所有参数

标签 java junit mockito rx-java rx-java2

我正在尝试测试 Single.zip(...) 调用每个参数,即使其中一个失败,但有时 verify 会失败,因为测试已完成在 Single.zip 之前执行...

我觉得 await 本质上应该是阻塞的,但情况似乎并不总是如此。我还缺少什么吗?

代码:

public Completable execute(String id) {
    return doThing()
        .flatMap(result -> Single.zip(
            employeeService.getEmployee(id),
            databaseService.getData(id),
            (employee, data) -> ...
         ))
         .toCompletable();
}

测试:

@Test
public void test() {
    Exception ex = new Exception("err");

    when(employeeService.getEmployee(anyString()).thenReturn(Single.error(ex));

    myObject.execute("id")
     .test()
     .await()
     .assertFailure(e -> e.equals(ex);

    verify(employeeService).getEmployee(eq("id"));
    verify(databaseService).getData(eq("id"));
}

可能的解决方案

  verify(employeeService, atLeast(0)).getEmployee(eq("id"));
  verify(employeeService, atMost(1)).getEmployee(eq("id"));
  verify(databaseService, atLeast(0)).getData(eq("id"));
  verify(databaseService, atMost(1)).getData(eq("id"));

最佳答案

I'm trying to test that Single.zip(...) calls every argument even if one fails, however sometimes verify will fail because the test has finished executing before Single.zip has...

这很难相信。我认为您的测试因其他原因而失败。

Single.zip(
        employeeService.getEmployee(id),
        databaseService.getData(id),
        (employee, data) -> ...

当这里调用Single.zip()时,employeeService.getEmployee(id)databaseService.getData(id)将会被调用甚至在控制权进入 Single.zip() 之前。

即使在控件进入该方法之前,也会首先评估方法调用的参数。因此,无论 Single.zip() 做什么,这两个方法都会被调用。

我认为您的测试失败了,因为 doThing() 中可能存在其他一些错误。

关于java - RxJava - 测试 Single.zip() 以确保执行所有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49918779/

相关文章:

java - 当测试不是Java方法时如何让Eclipse跳转到失败的JUnit测试

java - 模拟 JMS - jUnit

java - 我可以用哪个符号替换 "expected should equal("中的anyInt ""anyInt - anyInt - anyInt""")"

java - Selenium 测试运行不会保存 cookie?

java - 为数组按钮上的按钮设置 onclickListener 的最佳实践

java - Ant并行性能

java - 处理 apache poi 中的空列

java - 如何使用 Maven 运行特定包中的所有测试?

Spring MVC 测试 3.2.2 由于某些奇怪的原因失败 "flash().attributeExists"断言

java - 这是 Mockito spy 的正确案例吗?