首页 > 解决方案 > StepVerifier expectNoEvent for 0ms 不起作用(想检查特殊情况是否有延迟)

问题描述

我必须为每个客户创建一个背压,并通过返回一个Mono.justOrEmpty(authentication).delayElement(Duration.ofMillis(calculatedDelay));

这在我的单元测试中似乎工作正常,但如果我的计算延迟为 0,我无法测试它。此代码段返回一个java.lang.AssertionError: unexpected end during a no-event expectation

@Test
public void testSomeDelay_8CPUs_Load7() throws IOException {
  when(cut.getLoad()).thenReturn("7");
  when(cut.getCpuCount()).thenReturn(8L);
  when(authentication.getName()).thenReturn("delayeduser");

  Duration duration = StepVerifier
  .withVirtualTime(() -> cut.get(Optional.of(authentication))) 
  .expectSubscription()  // swallow subscribe event
  .expectNoEvent(Duration.ofMillis(0)) // here is the culprit
  .expectNextCount(1) 
  .verifyComplete(); 
}

我不知道如何检查这些案件,我预计不会有任何延误。顺便说一句,当我返回 Mono.justOrEmpty(authentication) (没有任何延迟订阅)时,这是一样的。我似乎无法检查,我是否创建了正确的非延迟流。

标签: spring-webfluxproject-reactor

解决方案


是的,这是一个很难覆盖的角落案例。特别是当您知道这foo.delayElement(0)实际上只是简单地返回foo未修改时。

您可以做的是通过附加elapsed()运算符以不同方式测试延迟:

Duration duration = StepVerifier
  .withVirtualTime(() -> cut.get(Optional.of(authentication))
     .elapsed() //this will get correct timing of 0 with virtual time
     .map(Tuple2::getT1) //we only care about the timing, T2 being the value
  ) 
  .expectNext(calculateDelay)
  .verifyComplete(); 

推荐阅读