liveBook · Manning

Cucumber EventListener

As explained in BDD in Action, Second Edition

A Cucumber EventListener is a plugin interface whose implementation registers handlers for events published during a Cucumber test run.

A Cucumber EventListener is a plugin interface for intervening in the test life cycle. Its implementation registers handlers for events such as test-run start and finish, providing a modular alternative to static initialization flags. section 8.5.2

Implementing one involves three practical steps:

  • Create a class implementing io.cucumber.plugin.EventListener. section 8.5.2
  • Implement setEventPublisher() and register handlers for the required events. section 8.5.2
  • Configure the listener class in the test runner’s plugin attribute. section 8.5.2

Managing a test database

A DatabaseServerHandler can start the database and initialize default flight plans when TestRunStarted occurs, then stop the server when TestRunFinished occurs. This keeps run-wide setup and cleanup together without relying on a static flag. section 8.5.2

Listing 8.25 Preparing data before any scenario is executed in Java using a static flag
public class DatabaseServerHandler implements EventListener {
    @Override
    public void setEventPublisher(EventPublisher eventPublisher) {
        eventPublisher.registerHandlerFor(TestRunStarted.class,       #1
                event -> {
                    TestDatabase.instance().startServer();
                    TestDatabase.instance().initialiseDefaultFlightPlans();
                });
 
        eventPublisher.registerHandlerFor(TestRunFinished.class,      #2
                event -> {
                    TestDatabase.instance().stopServer();
                });
    }
}

Inspect a complete listener that handles test-run start and finish events. section 8.5.2

How BDD in Action, Second Edition covers it

How deep it goes
Explains implementation, event registration, and runner configuration, but does not detail the event system beyond run-start and run-finish examples.
Examples
Demonstrates database initialization, server startup, server shutdown, and @CucumberOptions plugin registration.
What it assumes
Assumes familiarity with Cucumber test runs, Java classes, and test-runner configuration.
What you can do after
Build it from scratch to modularize run-wide setup and teardown in a Cucumber test suite.
How it connects
Connects hooks, event publishers, test-run events, parallel execution, and Cucumber test-runner configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of BDD in Action, Second Edition. The section links point to the parts of the book it draws on.