1、什么是Gherkin
Gherkin
是一种简单的英语文本语言, 它有助于工具--Cucumber解释和执行测试脚本。一个完整的测试脚本是由多个step
组成的,step
即最小单元。多个step
组成一个Scenario
,即一个完整的测试case
。多个Scenario
组成一个Feature
,即一组相关的测试case
。
2、关键字
主要关键字:
Feature
Rule
Example
(或Scenario
)Given
,When
,Then
,And
,But
步骤(或*
)Background
Scenario Outline
(或Scenario Template
)Examples
(或Scenarios
)
还有一些辅助关键字:
"""
(文档注释)|
(数据表、参数化)@
(标签)#
(注释)
2.1、 Feature
每一个.feature文件必须以关键字Feature开始,Feature关键字之后可以添加该feature的描述(这部分是可选的)。
Feature: 打开某东搜索手机加入购物车balabala
这些描述行会在运行时被Cucumber忽略,也就是说Cucumber并不care,但可用于报告(它们被包括在官方HTML格式器之类的报告工具中)
2.2、Rule
Rule
为非必要关键字,主要用作测试用例分组,例如:
Feature: Highlander Rule: There can be only One Scenario: Only One -- More than one alive Given there are 3 ninjas And there are more than one ninja alive When 2 ninjas meet, they will fight Then one ninja dies (but not me) And there is one ninja less alive Scenario: Only One -- One alive Given there is only 1 ninja alive Then he (or she) will live forever ;-) Rule: There can be Two (in some cases) Scenario: Two -- Dead and Reborn as Phoenix
在这个例子中,Rule: There can be only One
下有两个Scenario
,Rule: There can be Two (in some cases)
下只有一个Scenario
。
翻译来过:Only One -- More than one alive
和Only One -- One alive
属于同一组,写代码的时候确保两个用例都遵循Only One
规则,但是Cucumber并不会检查。
说白了类似于注释,告诉别人这两个测试用例遵循了某种规则。
2.3、Example
(或Scenario
)
Example
和Scenario
一样表示一个测试场景。
2.4、Given
,When
,Then
,And
,But
步骤(或*
)
Given
、When
、Then
在上一篇中已经介绍,这里介绍下And
和 But
。
And
和But
是为了替代连续Given
、When
、Then
。其中But
一般用作不期望的断言结果。
替换之后代码中的注解也要改成对应的@And
、@But
Scenario: Multiple Givens Given one thing Given another thing Given yet another thing When I open my eyes Then I should see something Then I shouldn't see something else 改造: Scenario: Multiple Givens Given one thing And another thing And yet another thing When I open my eyes Then I should see something But I shouldn't see something else
2.5、Background
当在同一个Feature里有多个Scenario有相同Given的时候,可以使用Background将这些Given抽到一起,简单来说就是抽取共性,让feature更简洁。例如:
Feature: 打开某东搜索手机加入购物车balabala Scenario: 手机加入购物车 Given 打开某东首页 When 搜索 小米手机 Then 是否显示 小米10Pro Scenario: 手机加入购物车 Given 打开某东首页 When 搜索 苹果手机 Then 是否显示 iphone12 使用Background后: Feature: 打开某东搜索手机加入购物车balabala Background: Given 打开某东首页 Scenario: 手机加入购物车 When 搜索 小米手机 Then 是否显示 小米10Pro Scenario: 手机加入购物车 When 搜索 苹果手机 Then 是否显示 iphone12
2.6、Scenario Outline
(或Scenario Template
)、Examples
(或Scenarios
)
Scenario Outline
一般和Examples
配合使用实现参数化,至于如何实现参数化,我们留到下一章讨论。
欢迎来到testingpai.com!
注册 关于