addeventlistenerjunit5event-listenercucumber-javacucumber-junit

Unable to implement Event Listener in latest Java Cucumber Maven project with JUnit5


Created a new Java Cucumber project with the command -

mvn archetype:generate "-DarchetypeGroupId=io.cucumber" "-DarchetypeArtifactId=cucumber-archetype" "-DarchetypeVersion=7.14.0" "-DgroupId=hellocucumber" "-DartifactId=hellocucumber" "-Dpackage=hellocucumber" "-Dversion=1.0.0-SNAPSHOT" "-DinteractiveMode=false"

Created a Custom Listener class with public class MyListener implements EventListener { . . . }

Since @CucumberOptions is not available in the latest version, can you please suggest how to register this MyListener class as a listener for execution ? This is to listen to events for - Before beginning the execution, After end of all scenarios etc.

Searched many blogs. But could not find relevant answers. Almost all blogs are referring to earlier versions of Cucumber where @CucumberOptions is available.


Solution

  • You can use the ConfigurationParameter annotation from JUnit 5 to set the cucumber.plugin property. For example:

    import org.junit.platform.suite.api.ConfigurationParameter;
    import org.junit.platform.suite.api.IncludeEngines;
    import org.junit.platform.suite.api.SelectClasspathResource;
    import org.junit.platform.suite.api.Suite;
    
    import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME;
    import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
    
    @Suite
    @IncludeEngines("cucumber")
    @SelectClasspathResource("io/cucumber/skeleton")
    @ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty")
    @ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "io.cucumber.skeleton")
    public class RunCucumberTest {
    }
    

    To target your plugin you would use the value your.package.MyListener, for multiple plugins you'd use a comma separated list.

    You can also set the cucumber.plugin property in the junit-platform.propeties file.

    It's worth reading the documentation from the JUnit Platform and Cucumbers JUnit Platform Engine: