
通过 cucumber 的标签(tags)结合 scenario outline 的 examples 表,可为多个网站(如 hotels.com、cars.com)复用同一业务场景,仅需按需激活对应数据集,无需重复编写 gherkin 代码。
通过 cucumber 的标签(tags)结合 scenario outline 的 examples 表,可为多个网站(如 hotels.com、cars.com)复用同一业务场景,仅需按需激活对应数据集,无需重复编写 gherkin 代码。
在 Spring Boot + Java 的 Cucumber 测试项目中,当需要对多个相似但数据不同的网站(例如 hotels.com 和 cars.com)执行相同的业务流程(如搜索功能),最佳实践是复用 Scenario Outline,通过带标签的 Examples 分组实现数据隔离与按需执行。
✅ 正确写法:为 Examples 添加专属标签
在 .feature 文件中,将不同网站的数据分别用带名称的 @tag 标注在 Examples 前,如下所示:
Feature: Search
@smoke @search
Scenario Outline: I want to search for products
Given I enter "<keyword>" as a keyword to a search field
Then I should see search results page
Then I should see at least <count> results containing "<keyword>"
@hotels
Examples:
| keyword | count |
| hotel | 3 |
@cars
Examples:
| keyword | count |
| cars | 3 |</keyword></count></keyword>
⚠️ 注意:@hotels 和 @cars 必须紧邻 Examples 关键字上方(中间不能有空行),且每个 Examples 块只能有一个标签;Cucumber 会将该标签绑定到整组示例行。
? 执行时按需筛选数据
运行测试时,通过 Cucumber 的 --tags 参数指定启用哪一组数据:
# 仅运行 hotels.com 相关示例 mvn test -Dcucumber.filter.tags="@hotels" # 仅运行 cars.com 相关示例 mvn test -Dcucumber.filter.tags="@cars" # 同时运行多个(用逗号分隔) mvn test -Dcucumber.filter.tags="@hotels or @cars"
若使用 JUnit 5,也可在测试类上通过 @SelectTags 或 @Tag 注解控制(需配合 Cucumber 运行器配置)。
? 进阶建议:增强可维护性
- 数据与逻辑分离:对于更复杂的多站点配置(如 baseURL、等待策略、登录方式等),建议将站点特定参数提取至 application-test.yml 或 @CucumberContextConfiguration 配合 Spring Profiles 管理,而非硬编码在 Examples 中。
- 避免标签冲突:确保 @hotels、@cars 等标签名全局唯一,并与 CI/CD 流水线中的环境标识保持一致(例如 @env=staging-hotels)。
- 验证标签生效:可在 Step Definition 中加入日志或断言,打印当前 Scenario.getId() 或 scenario.getSourceTagNames(),确认实际执行的是预期 Examples 组。
✅ 总结
Cucumber 原生支持「带标签的 Examples」机制,是实现跨站点场景复用最轻量、最标准的方案。它不依赖外部插件或自定义解析器,完全兼容 Spring Boot 的 Cucumber 集成(如 cucumber-spring),既保证了 Gherkin 的可读性,又提升了测试套件的可扩展性与可维护性。










