cucumbergherkincucumber-javafeature-file

Java Cucumber: How to get string parameter values from all the steps in a single scenario


I'm looking for a way to get all the parameters that are being passed in each step before entering the actual scenario for each scenario in my feature file.

Sample feature file:

Feature: Login action
  Background:
    When "{login url}" is open

  Scenario: Registered user provides valid username and password
    Given user enters username "{username}" and password "test password"
    And user clicks on "btnLogin"
    Then user is logged in

Parameters I want to get:

  • {login url}
  • {username}
  • password
  • btnLogin

    What I tried so far:

    I have tried using a common hook that will be automatically used by all of my scenarios:

    public class ScenarioHook {
    
        public ScenarioHook() {
        }
    
        @Before
        public void setupScenario(Scenario scenario) throws InterruptedException {
        //Here I am currently watching the {scenario} object and I can see all the steps
        //but I still dont know where to get the passed parameter values.
        }
    
        @After
        public void teardownScenario() throws InterruptedException {
        }
    }
    

    UPDATE 1: The reason why I want to do this is I want to manipulate the strings (if possible). e.g. all data enclosed in "{}" will be transformed to something else before entering the actual scenario.


  • Solution

  • You can use the @Transform annotation to change the value of the parameter to the step definition.

    For this you will need to create a class which contains the logic of the string modification and will return the modified value.

    public class StringTransformer extends Transformer<String>{
    
        public String transform(String value) {     
            return "transformed "+value;
        }    
    }
    

    Next you need to include this class in your stepdefinition using the @Transform annotation in front of the method argument.

       @When("^Login with (.*?)$")
            public void helloHere(@Transform(StringTransformer.class) String userName)
        {
                System.out.println("TEXT --- " + userName);
        }
    

    This should give you the new transformed string. You can use this to create objects from your initial string. (Actually that is what it is used for)