【问题标题】:Need help on writing a junit test for a function which is returning Flux stream as output在为返回 Flux 流作为输出的函数编写 junit 测试时需要帮助
【发布时间】:2019-11-20 02:11:56
【问题描述】:

在为将 Flux 流作为输出返回的函数编写单元测试时,我需要帮助。

我曾尝试使用 StepVerifier,但我想我使用它的方式有误。

需要测试以下功能。

public Flux<List<String>> streamCompletedScansAfterLastSubmit(@PathVariable("username") String username) {
    Flux<Long> interval = Flux.interval(Duration.ofSeconds(5));
    Flux<List<String>> completeScans = Flux.fromStream(Stream.generate(() -> scanService.getCompletedScansAfterLastSubmitForUser(username)));
    return Flux.zip(interval, completeScans).map(Tuple2::getT2);
  }

我试过的是

  public void shouldPublishTheAssessmentStatusOnceFinished() {
    when(scanService.getCompletedScansAfterLastSubmitForUser(Mockito.anyString())).thenReturn(Arrays.asList("Scan1:Success"));
    StepVerifier.create(apiScanController.streamCompletedScansAfterLastSubmit("quays_ka"))
      .expectSubscription()
      .expectNext(Arrays.asList("Scan1:Success"))
      .verifyComplete();
  }

我收到错误:

java.lang.AssertionError:预期“expectComplete”失败(预期:onComplete();实际:onNext([Scan1:Success]))

不知何故,服务方法被调用了两次(我使用 doAnswer 进行了检查)

【问题讨论】:

    标签: java spring-boot spring-webflux project-reactor


    【解决方案1】:

    Stream.generate(Supplier) 生成一个无限大的Stream,所以completeScans 也是无限大的。

    由于interval 也是无限的,因此使用模拟服务压缩这两个结果会生成一个Flux,它每5 秒发出一次["Scan1:Success"]

    相反,您的StepVerifier 在终止之前期望单个列表的Flux 非常有限,因此一旦看到该列表第二次出现,它就会失败。

    【讨论】:

    • 是的,目前修复了它,期望流中的元素数量有限并声明它们。 ``` StepVerifier.create(apiScanController.streamCompletedScansAfterLastSubmit("abc").take(2)) .expectNext(Arrays.asList("Scan1:Success")) .expectNext(Arrays.asList("Scan2:Error")) 。验证完成(); ```
    • 是的,这是一个好方法。您还可以在确信收到一致的值后取消源,方法是使用 thenCancel().verify() 而不是 verifyComplete()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多