BeforeMethod in Cucumber

412 views
Skip to first unread message

Anoop Halder

unread,
May 11, 2018, 7:58:19 AM5/11/18
to Cukes
Hello,
Is there any Hook Or annotation Or feature available in Cucumber that is equivalent to TestNG's @BeforeMethod annotation. I need to run a Check before each method(step definition) with any annotation like-(@Given,@When,@Then,@And etc..)
But '@Before' (cucumber.api.java.Before) hook is not fulfilling my this requirement as it runs only once for the scenario.


For example -

feature file-
Feature: Feature1 test

Scenario: Feature1 scenario1 (@Before will be executed)
Given Step for given  (@Before will not be executed) Here i want to add a check before starting this step 
When Step for when  (@Before will not be executed) Here i want to add a check before starting this step 
Then Step for then     (@Before will not be executed) Here i want to add a check before starting this step 


Nishant Vashisth

unread,
May 11, 2018, 8:11:59 AM5/11/18
to Cukes
If you're using info.cukes (which is an older version)

You can add custom formatter which can invoke a function before every step being executed

@CucumberOptions(
        features
= "src/main/resources",
        glue
= "com.bdd",
        plugin
= {"com.bdd.BDDCustomFormatter"},
        tags
= {"@match"})


Which can implement these two Interfaces
gherkin.formatter.Formatter
gherkin.formatter.Reporter

They have functions like

/**
     * Is called for each step of a step container. <b>Attention:</b> All steps are iterated through
     * this method before any step is actually executed.
     *
     * @param step the {@link Step} to be executed
     */

   
void step(Step step);

Which you can override to do whatever you want before every step.

If you're using newer versions of cucumber.io

You can implement cucumber.api.formatter.Formatter

And create event listeners

@Override
   
public void setEventPublisher(EventPublisher publisher) {

        publisher
.registerHandlerFor(TestCaseStarted.class, event -> {
            log
.info("Test Case Started");
       
});


        publisher
.registerHandlerFor(TestStepStarted.class, event -> {
            log
.info("Test Step Started");
       });

Reply all
Reply to author
Forward
0 new messages