Unit Test with Mono and Flux

Unit testing with Mono and Flux in Reactor Java is straightforward and involves the use of the StepVerifier class. The StepVerifier is a testing utility that can be used to verify the behavior of reactive streams.

Here’s an example of how to unit test a simple Mono:

@Test
public void testMono() {
    Mono<String> mono = Mono.just("Hello, world!");
    StepVerifier.create(mono)
            .expectNext("Hello, world!")
            .expectComplete()
            .verify();
}

 

Let’s create a simple Flux that emits three integer values. We use the StepVerifier to create a test scenario where we expect the Flux to emit the values 1, 2, and 3 in order, and then complete successfully.

@Test
public void testFlux() {
    Flux<Integer> flux = Flux.just(1, 2, 3);
    StepVerifier.create(flux)
            .expectNext(1)
            .expectNext(2)
            .expectNext(3)
            .expectComplete()
            .verify();
}

 

Verify with Errors

Let’s create a Mono and a Flux that both throw an error. We use the Mono.error and Flux.error methods to create the error conditions.

The expectErrorMatches allows one to examine if an error’s attributes are expected. The expectErrorMessage validates that the error message matches.

@Test
public void testMonoAndFluxWithError() {
    Mono<String> mono = Mono.error(new RuntimeException("Error!"));
    Flux<Integer> flux = Flux.error(new IllegalArgumentException("Invalid argument!"));

    StepVerifier.create(mono)
        .expectErrorMatches(throwable -> throwable.getMessage().equals("Error!"))
        .verify();

    StepVerifier.create(flux)
        .expectErrorMessage("Invalid argument!")
        .verify();
}

 

d