Cucumber:在每个功能文件中使用完全相同的小黄瓜设置步骤

Cucumber: Use the exact same gherkin setup step in every feature file

假设我有两个不同的特征:

我不会将 getupdate 这两个特征放入同一个特征文件中,因为它们在逻辑上不属于一起。但我能做的是:我可以使用相同的数据 - 相同的小黄瓜设置步骤:

Given there are the following entries in the database
    | id | value |
    | 1  | bla   |
    | 2  | blub  |

现在的问题是我无法为此创建 Background,因为我将拥有两个不同的功能:

Feature: Get
    // Here I want to use the given step which will be the same for each feature
    When ...
    Then ...
Feature: Update
    // Here I want to use the given step which will be the same for each feature
    When ...
    Then ...

如何设置黄瓜步骤,以便在每个功能中重用 given 小黄瓜步骤?

最好的方法是使用 Hooks。在您的 stepdefinition 包中创建一个 class(您不必将其称为钩子,但您可以),其中包含一个带有 @Before 标记的方法。它的运行方式与背景相同,但会 运行 跨越所有功能文件。确保从 Cucumber 而不是从 JUnit 导入那个。

public class Hooks {

  @Before
  public void doBefore(){
    //do things
  }
}

简单的解决方法就是在每个特征文件中调用该步骤。现在,如果这很乏味,因为你的步骤写得不好,有大量数据table,只需重写没有数据的步骤table。

以你的例子为例

Given there are the following entries in the database
    | id | value |
    | 1  | bla   |
    | 2  | blub  |

也改一下

Given bla and blub are in the database

通过这样做,您已将 HOW 从功能向下推到步骤定义。

假设您将其实现为

Given 'bla and blub are in the database' do
  db = get_connection
  ...
  db.insert(1, bla)
  db.insert(2, blub)
  ...
end

同样,您可以通过

降低 HOW

Given 'bla and blub are in the database' do
  add_bla_and_blub_to_db
end

现在正在使用辅助方法来执行您的实现。一旦你有了辅助方法,你就可以从其他步骤定义中调用它们。

TLDR 使您的步骤更简单,只需调用每个功能中的步骤。