问题
StepVerifier has an assertNext method that allows performing an assertion on a value of next element.
StepVerifier.create(dataFlux)
.assertNext(v -> checkValue(v)
.verifyComplete();
What is a good way to perform assertion for every remaining element (e.g. to check that every element is positive)? I'd expect something like assertEveryNextElement method.
回答1:
My first attempt to perform assertion on all elements of a flux was
StepVerifier.create(dataFlux)
.recordWith(ArrayList::new)
.thenConsumeWhile(x -> true) // Predicate on elements
.consumeRecordedWith(matches ->
matches.forEach(v -> checkValue(v)))
.verifyComplete();
UPD Simon Baslé suggested to use just thenConsumeWhile, it rethrows AssertionErrors.
StepVerifier.create(dataFlux)
.thenConsumeWhile(v -> {
assertThat(v).equalsTo(expected);
return true;
})
.verifyComplete();
And more canonical way to use StepVerifier for this task would be:
StepVerifier.create(dataFlux)
.thenConsumeWhile(v -> return expected.equals(v))
.verifyComplete();
回答2:
The expected way to do that is to actually use the thenConsumeWhile operator and provide a predicate. If there is any element in the sequence that doesn't match, the StepVerifier will error.
It is not assertion-based though, taking a Predicate rather than a Consumer. That said you could still use an assertion library, any AssertionError should fail the test (you still have to return a bogus predicate result).
(side warning: keep in mind this doesn't work well with infinite sequences)
来源:https://stackoverflow.com/questions/44762798/how-to-perform-assertion-on-all-remaining-elements-in-stepverifier