java - 如何在 cucumber-jvm 步骤之间传递变量

标签 java cucumber cucumber-jvm

为了在步骤之间传递变量,我让步骤方法属于同一个类,并使用类的字段来传递信息。

下面是一个例子:

Feature: Demo

  Scenario: Create user
    Given User creation form management
    When Create user with name "TEST"
    Then User is created successfully

带有步骤定义的Java类:

public class CreateUserSteps {

   private String userName;

   @Given("^User creation form management$")
   public void User_creation_form_management() throws Throwable {
      // ...
   }

   @When("^Create user with name \"([^\"]*)\"$")
   public void Create_user_with_name(String userName) throws Throwable {
      //...
      this.userName = userName;
   }

   @Then("^User is created successfully$")
   public void User_is_created_successfully() throws Throwable {
      // Assert if exists an user with name equals to this.userName
   }

我的问题是,在步骤之间共享信息是否是一种好习惯?或者最好将特征定义为:

Then User with name "TEST" is created successfully

最佳答案

为了在步骤之间共享共同点,您需要使用 World .在 Java 中,它不像在 Ruby 中那样清晰。

引用 Cucumber 的创建者。

The purpose of a "World" is twofold:

  1. Isolate state between scenarios.

  2. Share data between step definitions and hooks within a scenario.

How this is implemented is language specific. For example, in ruby, the implicit self variable inside a step definition points to the current scenario's World object. This is by default an instance of Object, but it can be anything you want if you use the World hook.

In Java, you have many (possibly connected) World objects.

The equivalent of the World in Cucumber-Java is all of the objects with hook or stepdef annotations. In other words, any class with methods annotated with @Before, @After, @Given and so on will be instantiated exactly once for each scenario.

This achieves the first goal. To achieve the second goal you have two approaches:

a) Use a single class for all of your step definitions and hooks

b) Use several classes divided by responsibility [1] and use dependency injection [2] to connect them to each other.

Option a) quickly breaks down because your step definition code becomes a mess. That's why people tend to use b).

[1] https://cucumber.io/docs/gherkin/step-organization/

[2] PicoContainer, Spring, Guice, Weld, OpenEJB, Needle

可用的依赖注入(inject)模块有:

  • cucumber 微型容器
  • cucumber 酱
  • cucumber -openejb
  • cucumber 春
  • cucumber 焊缝
  • cucumber 针

原帖在这里https://groups.google.com/forum/#!topic/cukes/8ugcVreXP0Y .

希望这会有所帮助。

关于java - 如何在 cucumber-jvm 步骤之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26422470/

相关文章:

java - 如何使用 jar 运行 cucumber ?

java - 如何使用 maven 运行 cucumber-jvm 测试

java - 为什么 "this"用作 RelativeLayout 构造函数中的参数?

java - Android ViewPager2中如何动态添加和删除页面?

java - 继承技术如何运作?

java - 四舍五入到 5 的倍数

java - 如何通过Cucumber从多个json文件中获取数据进行验证?

ruby - cucumber 中未初始化的常量 (NameError) - 如何将类包含到 _steps.rb?

ruby-on-rails - Cucumber 和/或 Webrat 讨厌?

java - Cucumber-JUnit,有没有办法控制@before和@after标签运行的顺序