How to verify with StepVerifier that provided Mono

2020-04-12 09:19发布

问题:

With StepVerifier it is very easy to check whether provided Mono has completed (just by expectComplete() method in StepVerifier), but what should I do if need to check the opposite case ?

I tried to use this approach:

    @Test
    public void neverMonoTest() {
        Mono<String> neverMono = Mono.never();
        StepVerifier.create(neverMono)
            .expectSubscription()
            .expectNoEvent(Duration.ofSeconds(1))
            .thenCancel()
            .verify();
    }

and such test passes. But this is false positive, because when I replace Mono.never() with Mono.empty() the test is still green.

Is there any better and reliable method to check lack of Mono's completion (of course within given scope of time) ?

回答1:

It looks like you're hitting a bug in reactor-test, and unfortunately one that doesn't look to be solved any time soon:

Due to my memory that was a constant flaw in design of reactor-test. Most likely that will be fixed once reactor-test will be rewritten from scratch / significantly.

Downgrading to 3.1.2 seems to fix the problem, but that's quite a downgrade. The only other workaround I'm aware of was posted by PyvesB here, and involves waiting for the Mono to timeout:

Mono<String> mono = Mono.never();
StepVerifier.create(mono.timeout(Duration.ofSeconds(1L)))
        .verifyError(TimeoutException.class);

When the next release rolls out, then you should be able to do:

Mono<String> mono = Mono.never();
StepVerifier.create(mono)
        .expectTimeout(Duration.ofSeconds(1));

...as a more concise alternative.