Gherkin - 只需重复使用Given语句作为When语句......可以接受吗?

Cha*_*man 8 bdd cucumber specflow gherkin behat

以下是三个示例BDD语句,可以帮助解释我的问题:

Scenario: User logs in
Given I am on the login screen
When I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
Then I should see the login successful page

Scenario: User buys a product
Given I am logged into the system using username "myUsername" and "myPassword"
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory
Run Code Online (Sandbox Code Playgroud)

VS

Scenario: User buys a product
Given I am on the login screen
And I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory
Run Code Online (Sandbox Code Playgroud)

所以上面的场景1很好,但最好的是声明2和3.声明2读得很好,更简洁.但我的步骤定义为"鉴于我使用用户名登录系统"myUsername"和"myPassword"将需要重复调​​用方案1调用的页面对象(或等效的)...似乎更多的开发工作.

所以真的只是想知道是否有人知道哪种是最佳做法.我在网上搜索过,发现了以下文件:http: //docs.behat.org/guides/1.gherkin.html

这个建议方案2是最好的,但后来写道:"验证用户(无交互建议的例外."先前发生的事情"没问题")"这有助于方案3.

干杯,

查理

Ben*_*ith 12

以下是我对您编写的方案的回顾.

场景1

Scenario: User logs in
Given I am on the login screen
When I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
Then I should see the login successful page
Run Code Online (Sandbox Code Playgroud)

优点:您正确使用Given,When和Then语句.在这种情况下,Given设置系统的初始状态,When表示用户将采取的操作,然后详细说明用于验证系统行为的断言.

缺点:虽然您所写的内容可行,但您遇到的问题是此测试很脆弱.如果您的公司要求在登录期间也必须指定与时间相关的安全令牌(例如),则必须添加另一个步骤来输入此附加字段.但是,如果你重写这个步骤是声明性的,例如

Given I am on the login screen
When I submit valid log-in criteria
Then I should see the login successful page
Run Code Online (Sandbox Code Playgroud)

然后,如果登录过程发生了变化,您只需要更改代码,方案将保持不变.

情景2

Scenario: User buys a product
Given I am logged into the system using username "myUsername" and "myPassword"
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory
Run Code Online (Sandbox Code Playgroud)

优点:与上述相同.

缺点:再次测试是脆弱的,因为它是必要的,即您指定了确切的登录凭据和特定产品.我将其重写为:

Given I am logged into the system
When I purchase a product
Then I should have that product in the product inventory
Run Code Online (Sandbox Code Playgroud)

您可以保存ScenarioContext.Current中 "When"步骤中指定的产品.然后,您可以在"Then"步骤中重复使用此值,以断言它存在于产品清单中.

场景3

Scenario: User buys a product
Given I am on the login screen
And I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory
Run Code Online (Sandbox Code Playgroud)

缺点:这是您最糟糕的情况,因为您错误地使用了Given语句.应该使用Given语句来定义测试的初始系统状态,因此在这种情况下"给定我在登录屏幕上"是正确的用法,但是"给定我输入有效的用户名"myUsername""是不正确的用法.它是不正确的,因为它表示用户操作,因此它应该由When覆盖.是的,您可以使用Given执行与When相同的编程步骤,但它不能正确执行!

我将此方案更改为我在方案2中建议的版本.