Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Cucumber, is it possible to programmatically get the current step being executed?

Tags:

java

cucumber

Scenario: As a user, I want to login to the system
Given I am on my website
When I enter valid credentials
Then I am taken to the home page

The scenario name can be retrieved using the getName() function. Is there a way to also get the step being executed (in Java)? We foresee the use of this in logging and reporting.

So, for the scenario above, I am on my website would be returned while the corresponding step definition is being executed.

like image 225
rs79 Avatar asked Oct 21 '25 13:10

rs79


2 Answers

I think the CucumberWithSerenity register a Listener which stores the current Step Name.

Try this in your Test-Runner:

//import net.serenitybdd.cucumber.CucumberWithSerenity;
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(...

And then in in your Step:

//import net.thucydides.core.model.TestStep;
//import net.thucydides.core.steps.StepEventBus;
if (!StepEventBus.getEventBus().isBaseStepListenerRegistered()) {
    return "Unknown"; // CucumberWithSerenity is required.
} 
String currentStepDescr = StepEventBus.getEventBus().getCurrentStep()
    .transform(TestStep::getDescription)
    .get();

Dependency:

<dependency>
    <groupId>net.serenity-bdd</groupId>
    <artifactId>serenity-core</artifactId>
    <version>${serenity.version}</version>
</dependency>
like image 53
Harald Brabenetz Avatar answered Oct 23 '25 04:10

Harald Brabenetz


I solved it using @BeforeStep & @AfterStep. It is a bit hacky, so use it only if you are know what you are doing.

public class StepDefBeginEndLogger {

private int currentStepDefIndex = 0;

@BeforeStep
public void doSomethingBeforeStep(Scenario scenario) throws Exception {

    Field f = scenario.getClass().getDeclaredField("testCase");
    f.setAccessible(true);
    TestCase r = (TestCase) f.get(scenario);

    //You need to filter out before/after hooks
    List<PickleStepTestStep> stepDefs = r.getTestSteps()
            .stream()
            .filter(x -> x instanceof PickleStepTestStep)
            .map(x -> (PickleStepTestStep) x)
            .collect(Collectors.toList());


    //This object now holds the information about the current step definition
    //If you are using pico container 
    //just store it somewhere in your world state object 
    //and to make it available in your step definitions.
    PickleStepTestStep currentStepDef = stepDefs
            .get(currentStepDefIndex);
}

@AfterStep
public void doSomethingAfterStep(Scenario scenario) {
    currentStepDefIndex += 1;
}

}

like image 22
Jernej Gorički Avatar answered Oct 23 '25 05:10

Jernej Gorički



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!