Show List

How Mono works

Mono is another core component of Project Reactor, representing a reactive stream emitting zero or one element. It's useful for scenarios where you have a single value to emit asynchronously over time, such as the result of a network request, a computation, or an optional value. Let's explore how Mono works with code examples and then write some test cases to test it.

How Mono Works:


import reactor.core.publisher.Mono; public class Main { public static void main(String[] args) { // Creating a Mono emitting a single value Mono<String> greetingMono = Mono.just("Hello, World!"); // Subscribing to the Mono to consume the emitted value greetingMono.subscribe( value -> System.out.println("Received value: " + value), // onNext callback error -> System.err.println("Error occurred: " + error), // onError callback () -> System.out.println("Mono completed") // onComplete callback ); } }

In this example:

  • We create a Mono named greetingMono emitting a single value "Hello, World!" using Mono.just().
  • We subscribe to the Mono using the subscribe() method, providing lambdas for handling the emitted value, errors, and completion.
  • When subscribed, the Mono emits the single value to the onNext callback, handles any errors in the onError callback, and signals completion in the onComplete callback.

Writing Test Cases for Mono:

To test the behavior of a Mono, we can also use the StepVerifier utility provided by Reactor Test. Here's how we can write test cases to verify the behavior of the greetingMono from the previous example:


import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; public class MonoTest { @Test public void testMonoBehavior() { // Creating the Mono emitting a single value Mono<String> greetingMono = Mono.just("Hello, World!"); // Verifying the behavior of the Mono using StepVerifier StepVerifier.create(greetingMono) .expectNext("Hello, World!") // Verifying the emitted value .expectComplete() // Verifying completion .verify(); // Triggering the verification } }

In this test case:

  • We create a Mono named greetingMono emitting a single value "Hello, World!".
  • We use StepVerifier.create() to create a StepVerifier for the greetingMono.
  • We chain expectNext() to verify the emitted value, expectComplete() to verify completion, and verify() to trigger the verification process.
  • If the Mono emits the expected value and completes successfully, the test case passes. Otherwise, it fails with appropriate error messages.

These test cases ensure that the Mono behaves as expected, emitting the correct value and completing successfully. They provide confidence in the behavior of reactive streams and help catch any unexpected issues or regressions in the code.


    Leave a Comment


  • captcha text