mmar
mmar

Reputation: 2020

How to pass variable & values between cucumber jvm scenarios

I have two scenarios A and B. I am storing the value of a field output of 'A' scenario in a variable. Now i have to use that variable in the Scenario 'B'. How can i pass a variable and its value from one scenario to other in Cucumber Java

Upvotes: 0

Views: 14951

Answers (4)

Gien
Gien

Reputation: 1

With static variables

public class CcumberCintext {
   public static String value;
}

Upvotes: 0

Mykola Gurov
Mykola Gurov

Reputation: 8695

Just for the record, instead of relying on static state one could use the Dependency Injection feature of cucumber-jvm.

Upvotes: 0

arin
arin

Reputation: 125

As mentioned by @Mykola, best way would be to use Dependency Injection. To give one simple solution using manual dependency injection, you could do something like

public class OneStepDefinition{

private String user;

// and some setter which could be your step definition methods

public String getUser() {
  return user;
}

}

public class AnotherStepDefinition {

private final OneStepDefinition oneStepDefinition;

 public AnotherStepDefinition(OneStepDefinition oneStepDefinition) {
        this.oneStepDefinition = oneStepDefinition;
    }

// Some step defs
@Given("^I do something on the user created in OneStepDefinition class$")
    public void doSomething() {
  String user = oneStepDefinition.getUser();
// do something with the user
    }
}

Upvotes: 0

David Baak
David Baak

Reputation: 934

It's not entirely clear if your step definitions for these scenarios are in separate classes, but I assume they are and that the step in ScenarioA is executed before the one in B.

public class ScenarioA {

  public static String getVariableYouWantToUse() {
    return variableYouWantToUse;
  }

  private static String variableYouWantToUse;

  Given("your step that expects one parameter")
  public void some_step(String myVariable)
    variableYouWantToUse = myVariable;
}

Then in scenario B.

public class ScenarioB {

  Given("other step")
  public void some_other_step()
    ScenarioA.getVariableYouWantToUse();
}

Upvotes: 2

Related Questions