有几种方法可以使您的 Gherkin 变得更好。

描述行为

您的场景应该描述系统的预期行为,而不是实现。换句话说,它应该描述*什么*,而不是*如何*。

例如,对于身份验证场景,您应该编写

When "Bob" logs in

而不是

  Given I visit "/login"
  When I enter "Bob" in the "user name" field
    And I enter "tester" in the "password" field
    And I press the "login" button
  Then I should see the "welcome" page

第一个示例,当“Bob”登录时,是一个*功能需求*。第二个,更长的示例,是一个*过程引用*。功能需求是特性,但过程属于实现细节。

这样,当特性的实现发生变化时,您只需要更改幕后的过程步骤。行为不必因为实现而改变。事实上,在编写特性条款时,问自己的一个好问题是:“如果实现发生变化,这个措辞需要改变吗?”

如果答案是“是”,那么您应该重新编写它,避免实现特定的细节。作为一项附带的好处,您的场景将因此变得更短,更易于理解和遵循。

考虑更声明式的风格

使场景更易于维护和更不易出错的一种方法是使用声明式风格。声明式风格描述应用程序的行为,而不是实现细节。声明式场景更像是“活文档”。声明式风格有助于您专注于客户获得的价值,而不是他们将使用的按键。

命令式测试传达细节,在某些情况下,这种测试风格是合适的。另一方面,由于它们与当前 UI 的机制紧密相连,因此通常需要更多工作才能维护。每次实现发生变化时,都需要更新测试。

以下是一个命令式风格的特性示例

Feature: Subscribers see different articles based on their subscription level 

Scenario: Free subscribers see only the free articles
  Given users with a free subscription can access "FreeArticle1" but not "PaidArticle1" 
  When I type "freeFrieda@example.com" in the email field
  And I type "validPassword123" in the password field
  And I press the "Submit" button
  Then I see "FreeArticle1" on the home page
  And I do not see "PaidArticle1" on the home page

Scenario: Subscriber with a paid subscription can access "FreeArticle1" and "PaidArticle1"
  Given I am on the login page
  When I type "paidPattya@example.com" in the email field
  And I type "validPassword123" in the password field
  And I press the "Submit" button
  Then I see "FreeArticle1" and "PaidArticle1" on the home page  

每个步骤都是一个精确的指令。输入和预期结果被精确地指定。但很容易想象应用程序的更改,这些更改将需要更改这些测试。免费和付费订阅的可用选项可能会改变。甚至登录方式也可能改变。如果将来用户使用语音界面或指纹登录怎么办?

更声明式的风格隐藏了应用程序功能实现的细节。

Feature: Subscribers see different articles based on their subscription level
 
Scenario: Free subscribers see only the free articles
  Given Free Frieda has a free subscription
  When Free Frieda logs in with her valid credentials
  Then she sees a Free article

Scenario: Subscriber with a paid subscription can access both free and paid articles
  Given Paid Patty has a basic-level paid subscription
  When Paid Patty logs in with her valid credentials
  Then she sees a Free article and a Paid article

使用声明式风格,每个步骤传达一个想法,但没有指定确切的值。*用户如何*与系统交互的细节,例如哪些特定文章是免费的或付费的,以及不同测试用户的订阅级别,是在步骤定义中指定的(与系统交互的自动化代码)。订阅套餐将来可能会改变。企业可以更改在免费和付费计划中向订阅者提供哪些内容,而无需更改此场景和其他使用相同步骤定义的场景。如果将来添加另一个订阅级别,则可以轻松地为此添加场景。通过避免诸如“点击按钮”之类的术语,这些术语暗示实现,场景对 UI 的实现细节更具弹性。即使以后实现发生变化,场景的意图也保持不变。此外,在场景中包含太多实现细节,会让人难以理解它所说明的预期行为。

您可以帮助我们改进此文档。 编辑此页面.