Search code examples
javaselenium-webdrivercucumbercucumber-jvmcucumber-java

Cucumber 5: Get step name from feature file excluding gherkin syntax (given, when, then, and)


So I need to get the test step descriptions after the gherkin syntax

Feature: User trades stocks   Scenario: User requests a sell before close of trading
Given I have 100 shares of MSFT stock
   And I have 150 shares of APPL stock
   And the time is before close of trading

So what I really need is to get the

I have 100 shares of MSFT stock

I have 150 shares of APPL stock

the time is before close of trading

I found these as I update the cucumber to v5.0.0-RC1:

Can someone help me with a snippet? What is the object that needs to be passed to the AfterStep and BeforeStep?


Solution

  • This is the code solution (in serviceHook class) for cucumber v4.3.1.

    PickleStepTestStep currentStep;
    private int counter = 0;
    
    @BeforeStep
    public void getStepName(Scenario scenario) throws Exception {
    
        Field f = scenario.getClass().getDeclaredField("testCase");
        f.setAccessible(true);
        TestCase r = (TestCase) f.get(scenario);
    
        List<PickleStepTestStep> stepDefs = r.getTestSteps()
                .stream()
                .filter(x -> x instanceof PickleStepTestStep)
                .map(x -> (PickleStepTestStep) x)
                .collect(Collectors.toList());
    
        currentStep = stepDefs.get(counter);
    
            System.out.println(currentStep.getStepText());
    
        }
    
    @AfterStep
    public void afterStep(Scenario scenario) {
        counter += 1;
    }