如何在 Cucumber Java 中的步骤之间传递变量值? [英] How to pass variable values between steps in Cucumber Java?

查看:26
本文介绍了如何在 Cucumber Java 中的步骤之间传递变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,我想在所有步骤中传递这个变量.任何人都可以通过代码片段示例建议如何在步骤之间传递变量值.任何帮助将不胜感激.

I have a variable and I want to pass this variable across all the steps. Anyone can suggest with an code snippet example please on how to pass a variable value between the steps please. Any help will be highly appreciated.

推荐答案

在 Cucumber for Java (cucumber-jvm) 中,在步骤之间共享数据的预期方式是使用依赖集成 (DI) 容器 - 其中一些已经与 Cucumber 集成.

In Cucumber for Java (cucumber-jvm) the intended way of sharing data between steps is to use a dependency integration (DI) container - several of which have been integrated with Cucumber.

使用 DI 的方法因容器而异,但这里有一个使用 PicoContainer 的示例:

The method in which you use DI varies slightly from container to container, but here's an example using PicoContainer:

// MySharedData.java
public class MySharedData {
    public String stringData;
}

// SomeStepDefs.java
public class SomeStepDefs {
    private MySharedData sharedData;

    public SomeStepDefs(MySharedData sharedData) {
        this.sharedData = sharedData;
    }

    // StepDefs omitted
}

// MoreStepDefs.java
public class MoreStepDefs {
    private MySharedData sharedData;

    public MoreStepDefs(MySharedData sharedData) {
        this.sharedData = sharedData;
    }

    // StepDefs omitted
}

DI 容器将确保为 each 场景创建一个 MySharedData 的单个实例,并将其传递给 every 需要的步骤定义类它.这种方法的好处是 Cucumber 确保场景之间没有共享状态泄漏,因为注入的依赖项是为每个场景重新创建的.

The DI container will ensure that a single instance of MySharedData is created for each scenario and is passed to every step definition class that requires it. The benefit of this approach is that Cucumber ensures that no shared state leaks between scenarios, because the injected dependency is created afresh for each scenario.

上面的例子使用了构造函数注入(所以注入的依赖是由构造函数参数指定的)但是其他DI容器也支持其他注入机制,例如Spring的@Autowired.

The example above uses constructor injection (so the injected dependency is specified by a constructor parameter) but other DI containers also support other injection mechanisms, such as Spring's @Autowired.

要让 Cucumber 使用 DI,您需要选择一个(并且只有一个)DI 集成并将其包含在您的类路径(或您的 POM)中.选择是:

To get Cucumber to use DI you'll need to choose one (and only one) of the DI integrations and include it on your classpath (or in your POM). The choice is between:

  • PicoContainer (cucumber-picocontainer.jar)
  • Guice (cucumber-guice.jar)
  • 焊接 (cucumber-weld.jar)
  • 春天 (cucumber-spring.jar)
  • OpenEJB (黄瓜-openejb.jar)

您还需要安装所选的 DI 容器本身,因为 Cucumber jar 仅提供 Cucumber 和 DI 容器之间的集成.

You'll also need to install the selected DI container itself, because the Cucumber jars only provide the integration between Cucumber and the DI container.

这篇关于如何在 Cucumber Java 中的步骤之间传递变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆