Reactively Writing Unit Tests for Methods
Explore how to effectively write unit tests for reactive methods in Spring Boot using JUnit 5 and Project Reactor. Understand mocking collaborators, verifying asynchronous flows with StepVerifier, and handling both successful and failure test scenarios.
We'll cover the following...
Let’s write unit tests to test our methods in this lesson.
Testing a method
Domain objects aren’t too hard to test. Things get trickier when exercising code that interacts with other components. A good example is our InventoryService. This class contains several operations that have business logic and also interact with external collections through repositories.
On top of that, this service is the first level that has asynchronous, non-blocking flows, thanks to Project Reactor. So how exactly do we test that?
Never fear, Spring Boot and Project Reactor provide us with the tools to empower JUnit to verify that all is well.
To sharpen our focus, let’s test InventoryService.addItemToCart(...). We can start by creating a new test class called InventoryServiceUnitTest, like this:
-
In line 1, we can see that the
@ExtendWithis JUnit 5’s API to register custom test handlers. TheSpringExtensionis Spring Framework’s hook for Spring-specific test features. -
In line 2, we can see that, by combining the name of the class under test (
InventoryService) with the scope of the test (UnitTest), the name clearly denotes what’s being tested in this class.
With our test class declared, it’s now important to identify what’s being tested, and what isn’t. This is known as the class under test. For unit testing, any outside service or component has been dubbed a collaborator and should be mocked or stubbed away.
Inside InventoryServiceUnitTest, let’s declare these mock ...