How to pass variable & values between cucumber jvm scenarios

喜你入骨 提交于 2019-12-23 05:50:35

问题


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


回答1:


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();
}



回答2:


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
    }
}



回答3:


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



来源:https://stackoverflow.com/questions/36918616/how-to-pass-variable-values-between-cucumber-jvm-scenarios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!