Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve all flux elements in StepVerifier

I am working on testing a flux. I don't know how many elements exactly the flux has. Initially I have tried with StepVerifier and faced issues as i do not know the elements. Later I have referred this question and tried the same but I am getting the below error: java.lang.AssertionError: expectation "expectComplete" failed (expected: onComplete(); actual: onNext

My understanding is that, my code is expecting a complete signal but the flux has some more elements left(so it gives onNext() instead of onComplete()). Please help me to understand where I am missing things. Below is my code:

StepVerifier.create(flux)
            .recordWith(ArrayList::new)
            .consumeRecordedWith(elements-> {assertThat(elements.size()).isGreaterThan(0);})
            .verifyComplete();
like image 854
Antony Vimal Raj Avatar asked Jul 26 '19 13:07

Antony Vimal Raj


1 Answers

You're not actually consuming your Flux, you're just setting up what happens when it's consumed. Your verifyComplete(); call then fails, understandably, because the Flux hasn't been consumed at all, and it's thus not complete!

You need to add a thenConsumeWhile() call to actually consume it.

If you really need to use AssertJ as you do above, then you can do:

StepVerifier.create(flux)
        .recordWith(ArrayList::new)
        .thenConsumeWhile(x -> true)
        .consumeRecordedWith(elements -> {
            assertThat(elements.isEmpty()).isFalse();
        })
        .verifyComplete();

However, there's no need for AssertJ here - the reactor test package is enough, and adding additional testing frameworks makes the testing code much less clear IMHO. So if you're not wedded to AssertJ, just do:

StepVerifier.create(flux)
        .recordWith(ArrayList::new)
        .thenConsumeWhile(x -> true)
        .expectRecordedMatches(elements -> !elements.isEmpty())
        .verifyComplete();

Note that in real-world use, you'd probably want to adjust the predicate in thenConsumeWhile so that it runs a check against each element in turn, too. I've also adjusted the above code to use isEmpty() rather than checking if size()>0, as it's semantically clearer while achieving the same purpose.

like image 133
Michael Berry Avatar answered Jan 02 '23 16:01

Michael Berry