Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll discuss testing code that uses Spring application events. We’ll start by manually creating test utilities that help us publish and collect application events for testing purposes.

After that, we’ll discover Spring Modulith‘s testing library and use its fluent Scenario API to discuss the common test cases. Using this declarative DSL, we’ll write expressive tests that can easily produce and consume application events.

2. Application Events

Spring Framework offers application events to allow components to communicate with each other while maintaining a loose coupling. We can use the ApplicationEventPublisher bean to publish internal events, which are plain Java objects. Consequently, all the registered listeners are notified.

For example, the OrderService component can publish an OrderCompletedEvent when an Order is placed successfully:

@Service
public class OrderService {

    private final ApplicationEventPublisher eventPublisher;
    
    // constructor

    public void placeOrder(String customerId, String... productIds) {
        Order order = new Order(customerId, Arrays.asList(productIds));
	// business logic to validate and place the order

	OrderCompletedEvent event = new OrderCompletedEvent(savedOrder.id(), savedOrder.customerId(), savedOrder.timestamp());
	eventPublisher.publishEvent(event);
    }

}

As we can see, the completed orders are now published as application events. Therefore, components from different modules can now listen to these events and react accordingly.

Let’s assume that LoyaltyPointsService reacts to these events to reward customers with loyalty points. To implement this, we can leverage Spring’s @EventListener annotation:

@Service
public class LoyaltyPointsService {

    private static final int ORDER_COMPLETED_POINTS = 60;

    private final LoyalCustomersRepository loyalCustomers;

    // constructor

    @EventListener
    public void onOrderCompleted(OrderCompletedEvent event) {
        // business logic to reward customers
        loyalCustomers.awardPoints(event.customerId(), ORDER_COMPLETED_POINTS);
    }

}

Using application events instead of a direct method invocation allowed us to keep a looser coupling and invert the dependency between the two modules. In other words, the “orders” module doesn’t have source code dependencies on the classes from the “rewards” module.

3. Testing Event Listeners

We can test a component that uses @EventListener by publishing an application event from within the test itself.

To test LoyaltyPointsService, we’ll need to create a @SpringBootTest, inject the ApplicationEventPublisher bean, and use it to publish an OrderCompletedEvent:

@SpringBootTest
class EventListenerUnitTest {

    @Autowired
    private LoyalCustomersRepository customers;

    @Autowired
    private ApplicationEventPublisher testEventPublisher;

    @Test
    void whenPublishingOrderCompletedEvent_thenRewardCustomerWithLoyaltyPoints() {
        OrderCompletedEvent event = new OrderCompletedEvent("order-1", "customer-1", Instant.now());
        testEventPublisher.publishEvent(event);

	// assertions
    }

}

Finally, we need to assert that LoyaltyPointsService consumed the event and rewarded the customer with the correct number of points. Let’s use LoyalCustomersRepository to see how many loyalty points were awarded to this customer:

@Test
void whenPublishingOrderCompletedEvent_thenRewardCustomerWithLoyaltyPoints() {
    OrderCompletedEvent event = new OrderCompletedEvent("order-1", "customer-1", Instant.now());
    testEventPublisher.publishEvent(event);

    assertThat(customers.find("customer-1"))
      .isPresent().get()
      .hasFieldOrPropertyWithValue("customerId", "customer-1")
      .hasFieldOrPropertyWithValue("points", 60);
}

As expected, the test passes: the event is received and processed by the “rewards” module, and the bonus is applied.

4. Testing Event Publishers

We can test a component that publishes application events by creating a custom event listener in the test package.  This listener will also use the @EventHandler annotation, similar to the production implementation. However, this time we’ll collect all the incoming events into a list that will be exposed via a getter:

@Component
class TestEventListener {

    final List<OrderCompletedEvent> events = new ArrayList<>();
    // getter

    @EventListener
    void onEvent(OrderCompletedEvent event) {
        events.add(event);
    }

    void reset() {
        events.clear();
    }
}

As we can observe, we can also add the utility reset(). We can call it before each test, to clear the events produced by the previous one. Let’s create the Spring Boot test and @Autowire our TestEventListener component:

@SpringBootTest
class EventPublisherUnitTest {

    @Autowired
    OrderService orderService;

    @Autowired
    TestEventListener testEventListener;

    @BeforeEach
    void beforeEach() {
        testEventListener.reset();
    }

    @Test
    void whenPlacingOrder_thenPublishApplicationEvent() {
        // place an order

        assertThat(testEventListener.getEvents())
          // verify the published events
    }

}

To finish the test, we’ll need to place an order using the OrderService component. After that, we’ll assert that testEventListener received exactly one application event, having adequate properties:

@Test
void whenPlacingOrder_thenPublishApplicationEvent() {
    orderService.placeOrder("customer1", "product1", "product2");

    assertThat(testEventListener.getEvents())
      .hasSize(1).first()
      .hasFieldOrPropertyWithValue("customerId", "customer1")
      .hasFieldOrProperty("orderId")
      .hasFieldOrProperty("timestamp");
}

If we look closely, we’ll notice that the setup and verification of these two tests complement each other. This test simulates a method call and listens for the published event, whereas, the previous one publishes an event and verifies a state change. In other words, we’ve tested the entire process by using just two tests: each one covering a distinct segment, split at the logical module boundary.

5. Spring Modulith’s Test Support

Spring Modulith offers a collection of artifacts that can be used independently. These libraries provide a range of functionalities primarily aimed at establishing clear boundaries between logical modules within an application.

5.1. The Scenario API

This architectural style promotes a flexible interaction between modules by utilizing application events. Therefore, one of the artifacts within the Spring Modulith offers support for testing flows that involve application events.

Let’s add spring-modulith-starter-test maven dependency to our pom.xml:

<dependency>
    <groupId>org.springframework.modulith</groupId>
    <artifactId>spring-modulith-starter-test</artifactId>
    <version>1.1.3</version>
</dependency>

This allows us to write tests in a declarative way, using the Scenario API. First, we’ll create a test class and annotate it with @ApplcationModuleTest. As a result, we’ll be able to inject the Scenario object in any of the test methods:

@ApplicationModuleTest
class SpringModulithScenarioApiUnitTest {
 
    @Test
    void test(Scenario scenario) {
        // ...
    }

}

Simply put, this feature offers a convenient DSL that allows us to test the most common use cases. For example, it makes it easy to initiate the test and evaluate its outcome by:

  • performing method calls
  • publishing application events
  • verifying state changes
  • capturing and verifying outgoing events

Additionally, the API offers a few other utilities, such as:

  • polling and waiting for asynchronous application events
  • defining timeouts
  • perform filtering and mapping on the captured events
  • creating custom assertions

5.2. Testing Event Listeners Using Scenario API

To test components using @EventListener methods, we had to inject the ApplicationEventPublisher bean and publish an OrderCompletedEvent. However, Spring Modulith’s test DSL provides a more straightforward solution via scenario.publish():

@Test
void whenReceivingPublishOrderCompletedEvent_thenRewardCustomerWithLoyaltyPoints(Scenario scenario) {
    scenario.publish(new OrderCompletedEvent("order-1", "customer-1", Instant.now()))
      .andWaitForStateChange(() -> loyalCustomers.find("customer-1"))
      .andVerify(it -> assertThat(it)
        .isPresent().get()
        .hasFieldOrPropertyWithValue("customerId", "customer-1")
        .hasFieldOrPropertyWithValue("points", 60));
}

The method andWaitforStateChange() accepts a lambda expression and it retries executing it until it returns a non-null object or a non-empty Optional. This mechanism can be particularly useful for asynchronous method calls.

To conclude, we defined a scenario where we publish an event, wait for a state change, and then, verify the final state of the system. 

5.3. Testing Event Publishers Using Scenario API

We can also use the Scenario API to simulate a method call, and intercept, and verify outgoing application events. Let’s use the DSL to write a test that validates the behavior of the “order” module: 

@Test
void whenPlacingOrder_thenPublishOrderCompletedEvent(Scenario scenario) {
    scenario.stimulate(() -> orderService.placeOrder("customer-1", "product-1", "product-2"))
      .andWaitForEventOfType(OrderCompletedEvent.class)
      .toArriveAndVerify(evt -> assertThat(evt)
        .hasFieldOrPropertyWithValue("customerId", "customer-1")
        .hasFieldOrProperty("orderId")
        .hasFieldOrProperty("timestamp"));
}

As we can see, the method andWaitforEventOfType() allows us to declare the type of event we want to capture. Following that, toArriveAndVerify() is used to wait for the event and perform the relevant assertions.

6. Conclusion

In this article, we saw various ways of testing code using Spring application events. In our first test, we used an ApplicationEventPublisher to manually publish the application events.

Similarly, we created a custom TestEventListener that uses the @EventHandler annotation to capture all the outgoing events. We used this helper component to capture and verify the events produced by our application during the test.

After that, we learned about Spring Modulith’s testing support and we used the Scenario API to write the same tests in a declarative fashion. The fluent DSL allowed us to publish and capture application events, simulate method calls, and await state changes.

As always, the complete source code can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments