Write Unit Test for Project Reactor using class StepVerifier

Project Reactor with Mono and Flux objects may make it difficult for you to think about how to write Unit Test for reactive code. Actually, this will be solved easily if you use the StepVerifier class of the reactor-test library. How is it in details? In this tutorial, I will show you how to write Unit Test for Project Reactor using the StepVerifier class!

First, I will create a Maven project as an example:

Write Unit Test for Project Reactor using class StepVerifier

with reactor-test dependency is declared as follows:

Of course, we also need to declare additional dependencies to write Unit Test:

To write Unit Test for reactive code, we will use the StepVerifier class to subscribe to the producer and then use the methods supported by the StepVerifier class to assert the desired results in the subscription.

Suppose now I have a simple method of returning Mono object as follows:

I will write a Unit Test code for this class using the StepVerifier class as follows:

As you can see, we will use the create() method of the StepVerifier class to subscribe to the producer. For the Mono object, because it contains only one element, normally we will use the expectNext() method to get this element and assert its value.

One point you should note is that after adding the assertions have completed, you need to call the verifyComplete() method to unsubscribe the producers!

The Flux object is similar! For example, I have the following method:

The test method for the above method will be as follows:

The result after running the above test methods will be as follows:

Write Unit Test for Project Reactor using class StepVerifier

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment