How to add listeners to the Cucumber test automation framework (5/7)

The following articles will focus on an extending functionality of the automation framework. We are going to start from a basics — listeners.

As usual, code from this chapter can be found here.

Photo by Jelleke Vanooteghem Unsplash

Listeners

According to definition, an event listener is a function that waits for an event to occur.

Why it is important?

Listeners its easiest way to add additional functionality to the framework (test execution framework like TestNg or Cucumber) without them code modification. Instead, new methods will be executed on particular situations, such as test run start, test case execution or failing test.

Cucumber has limited listeners supports (default @Before and @After annotations for the step methods). Instead, we will use Cucumber plugins system.

To create a plugin, we need:
1. Create class and implement ConcurrentEventListener interface,
2. Add plugin to the Cucumber options.

Implement Cucumber plugin

Cucumber plugins implementation fully based on an idea of listeners. Documentation about events publishers can found here.

Create class ListenerPlugin:

ConcurrentEventListener interface contains one method setEventPublisher, which allows to link the events, occurring in the framework and the methods which will be executed.

Let`s create method which prints current test step name and test execution start and finish timestamp. We will create three methods: onTestRunStarted, onTestRunFinished and onTestCaseStarted.

Then, we connect this method with the events:

Final version of the ListenerPlugin:

Add Cucumber plugin to the configuration

We need to say Cucumber to use this plugin.

Add created plugin Class to the plugin option to the @CucumberOptions:

But when test is executed via IDE this file is not taken by Cucumber. We need to add plugin option to the RunConfiguration.

Add “--plugin listener.ListenerPlugin” to the Cucumber Java template and created Cucumber test runs will contain this parameter and will use created plugin.

Execute the tests

Execute system.feature file. Console output will contain messages from the ListenerPlugin:

At the next article we will utilize listeners for the HTML and logs reporting.

--

--

Test automation engineer, writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store