eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)