在定义Gherkin Given和When语句时避免代码重复

时间:2014-01-14 10:19:37

标签: tdd cucumber bdd gherkin scenarios

我提出了类似的问题,但措辞严厉,所以没有真正得到我追求的答案。这是另一种尝试:

所以我很欣赏Cucumber的Gherkin Given声明类似于测试用例的前提条件。我感谢有些人觉得这些不应该涉及用户互动,但为了这个问题,我将不同意这种观点。

以下是三种情况:

Scenario: Test a song can be played
Given I setup a new account and default user
When I add a "2nd" user
And the "2nd" user starts playing a song
Then I should see a song is playing

Scenario: Test a playing song being stopped (version A)
Given I setup a new account and default user
And I add a "2nd" user
And the "2nd" user starts playing a song
When the "2nd" user stops playing a song
Then I should see a song is not playing

Scenario: Test a playing song being stopped (version B)
Given a "2nd" user is playing a song
When the "2nd" user stops playing a song
Then I should see a song is not playing

所以我感谢上面的版本B从业务用户点比版本A更好。但是,从代码重用的角度来看,版本B肯定需要Given语句来重复大多数代码中使用的代码。第一种情况?

干杯,

查理

1 个答案:

答案 0 :(得分:1)

所以版本B是最适合的。

如果给定的步骤定义(例如版本B)具有由其他步骤定义(例如第一个场景)中涵盖的步骤组成的动作,我只需在步骤定义中创建一个私有方法(或者如果在步骤定义文件中使用的话,则在别处创建一个私有方法) )Given和When语句都可以根据需要调用。这消除了复制和粘贴代码的需要: - )