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
