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
namedgreetingMono
emitting a single value"Hello, World!"
usingMono.just()
. - We subscribe to the
Mono
using thesubscribe()
method, providing lambdas for handling the emitted value, errors, and completion. - When subscribed, the
Mono
emits the single value to theonNext
callback, handles any errors in theonError
callback, and signals completion in theonComplete
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
namedgreetingMono
emitting a single value"Hello, World!"
. - We use
StepVerifier.create()
to create a StepVerifier for thegreetingMono
. - We chain
expectNext()
to verify the emitted value,expectComplete()
to verify completion, andverify()
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