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
4 Answers
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();
}
Comments
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
}
}
1 Comment
MushyPeas
The question was about scenarios not steps, DI does not work for scenarios.
Just for the record, instead of relying on static state one could use the Dependency Injection feature of cucumber-jvm.
1 Comment
SiKing
The link is dead Jim!