如何在 Gherkin 中实现 'if'

How to implement 'if' in Gherkin

我正在尝试将 Selenium 测试转换为 Gherkin。有没有办法在 Gherkin 中实现 if 语句?

示例:假设代码是按以下格式编写的。我只是写描述如下。请理解双斜线后的部分是实际的 Selenium 代码:​​

// launch the application 
// login to application
// navigate to page
String str;
if(str== "XYZ")
{
    // verify title
}
//verify text field 1
//verify test field 2
//verify select box

为此,我尝试在 Gherkin 中编写如下代码

Given user launches the application
When user login with valid credentials
and navigate to required page
When String str is "XYZ"
Then verify title
And verify text field 1
And verify test field 2
And verify select box

但此代码不正确,因为如果 str 不等于 "XYZ",我们希望不验证该标题,但应验证文本字段 1、2 和 select 框等其他验证。

严格来说,您应该按照以下行创建替代语句:

Given user launches the application When user login with valid credentials and navigate to required page When String str is NOT "XYZ"

理想情况下,这种详细程度不会出现在您的 Gherkin 场景中。最好的方法是描述业务用例,而不是底层细节。这就是 Gherkin 的设计目的:与非技术利益相关者沟通,以便您可以确定您是否首先构建了正确的东西。这是我要写的内容:

Given the user is logged in
And the user is on the required page
When they enter data that requires the optional fields to be validated
And they enter invalid data in the optional fields
Then the form shows an error on the optional fields

底层细节无关紧要(字符串具体是 "XYZ" 还是 title 字段并不重要),因此这些应该隐藏在步骤定义中 and/or 单元测试。

为了继续检查其他字段,您可以在这之后再添加一个步骤:

When they enter invalid data in all of the other fields
Then each other field has an error message attached to it.

同样,无需指定实际字段,或将它们分成各自的步骤。这个想法是为了表达场景的高级商业价值,即表单在应该的时候得到验证。

保持高水平的好处是,当表单发生变化时(最终可能会发生变化),这种情况可以保持不变。这是正确的,因为业务案例是相同的:它应该在应该验证的时候验证。所有更改都将在步骤定义中。这意味着没有理由与您的利益相关者再次讨论您的方案是否仍在测试正确的事情。

你可以这样写场景:

Given the user launches the application
When user login with valid credentials
And navigates to required page
Then he should see the page datails

Then 步骤中,您管理所有逻辑。

Then(/^he should see the page details$/) do
  if condition
    ...
  else
    ...
  end
end

Gherkin 不是一种使用 ifelse 条件的编程语言。它是 BDD 框架的一部分,已实施,以使利益相关者和其他非技术资源了解测试过程的内容。因此,始终建议您使小黄瓜尽可能简单和通用。

你没有在 Gherkin 中实现 if。

Gherkin 是关于交流的,那些你想与之交流的非编码人员不知道 if 语句是什么。他们也不在乎。

解决办法?涵盖两种情况的两种情况。