BDD负向测试场景编写及前置条件放入Before()钩子相关问题咨询
BDD测试场景编写指导
一、负向场景编写方案
不建议在单个场景中完成所有缺省情况的校验:BDD场景核心要求是单一校验点,单个场景覆盖多规则时,一旦执行失败无法快速定位是哪项缺省校验失效。
你可以根据场景量级选择两种编写方式:
方式1:独立场景编写(适合规则少、要求可读性极强的场景)
Scenario: Disable Add to Favorites button when size is not selected When the consumer is viewing an item And the consumer selects an item And the consumer does NOT select a size And the consumer selects a quantity Then the Add to Favorites button remains disabled Scenario: Disable Add to Favorites button when quantity is not selected When the consumer is viewing an item And the consumer selects an item And the consumer selects a size And the consumer does NOT select a quantity Then the Add to Favorites button remains disabled Scenario: Disable Add to Favorites button when item is not selected When the consumer is viewing an item list And the consumer does NOT select an item And the consumer selects a size And the consumer selects a quantity Then the Add to Favorites button remains disabled
方式2:场景大纲参数化编写(适合规则多、需要减少重复代码的场景)
通过参数化缺省项实现所有缺省情况的覆盖,执行失败时会直接提示对应校验项,定位效率和独立场景一致:
Scenario Outline: Disable Add to Favorites button when any required field is missing When the consumer is viewing an item And the consumer <item_status> an item And the consumer <size_status> a size And the consumer <quantity_status> a quantity Then the Add to Favorites button remains disabled Examples: | item_status | size_status | quantity_status | | selects | does NOT select | selects | | selects | selects | does NOT select | | does NOT select | selects | selects |
二、公共前置条件是否适合放入Before()钩子
不建议直接把三个必要前置放入Before()钩子,原因如下:
- 隐式前置会降低场景可读性:BDD场景本身需要作为可阅读的业务文档,其他维护人员看不到
Before()里的逻辑,无法直接通过场景描述理解前置条件 - 兼容性差:如果测试套件同时包含负向场景,
Before()里的全量设置会和负向场景需要的缺省条件冲突,需要额外做清除操作,反而增加冗余 - 灵活性低:如果后续新增场景需要调整其中某一项前置的参数,硬编码在
Before()里的逻辑很难复用
推荐方案
把三个前置条件封装为可复用的公共步骤,比如:
Given 消费者已完成商品、尺码、数量的全部选择
需要用到的正向场景直接调用该步骤即可,兼顾复用性和可读性。如果你的测试套件是仅跑正向校验的专属测试集,没有任何负向或特殊前置的场景,才可以考虑将公共前置放入Before()钩子。
内容的提问来源于stack exchange,提问作者Mike S.
相关产品推荐
相关产品推荐

