如何定义Cucumber测试用例执行顺序?场景执行顺序控制解析
问题描述
我在同一个feature文件中包含两个不同的Scenario,要求添加新ExhPlan场景必须在删除ExhPlan场景之前执行。我了解到可通过Cucumber Hooks实现此需求,但未找到具体的Cucumber实现示例。当前场景执行顺序符合预期,但我不清楚手里的Hooks文件是如何控制执行顺序的。
提供的代码
Feature文件
@Events @InsertExhPlan @DelExhPln Feature: Insert an Exh Plan and then delete it @InsertExhPlan Scenario: Add a new ExhPlan Given I login as admin And I go to automated test When I go to ExhPlan section And Insert a new exh plan Then The exh plan is listed @DeleteExhPlan Scenario: Delete an Exh Plan Given I login as admin And Open the automatized tests edition When I go to the exh plan section And The new exh plan is deleted Then The new exhibitor plan is deleted
Hooks文件
package com.barrabes.utilities; import cucumber.api.java.After; import cucumber.api.java.Before; import static com.aura.steps.rest.ParentRestStep.logger; public class Hooks { @Before(order=1) public void beforeScenario(){ logger.info("================This will run before every Scenario================"); } @Before(order=0) public void beforeScenarioStart(){ logger.info("-----------------Start of Scenario-----------------"); } @After(order=0) public void afterScenarioFinish(){ logger.info("-----------------End of Scenario-----------------"); } @After(order=1) public void afterScenario(){ logger.info("================This will run after every Scenario================"); } }
问题解答
首先明确:你当前的Hooks文件并没有控制两个Scenario的执行顺序,当前顺序符合预期只是因为Cucumber默认会按照feature文件里的场景定义顺序执行。
1. 现有Hooks的实际作用
Hooks中@Before和@After注解的order参数,控制的是多个Hook方法之间的执行优先级,而非Scenario本身的执行顺序:
@Before(order=0)会比@Before(order=1)先执行(order值越小,优先级越高)@After(order=0)会比@After(order=1)先执行(After的order值越小,越先触发)
你的Hooks只是在每个Scenario前后打印日志,和场景执行顺序完全无关。
2. 确保添加场景优先执行的可行方案
方案一:强制按feature定义顺序执行
在Cucumber配置文件(比如cucumber.properties)中添加以下配置,让Cucumber严格按照feature文件里的场景顺序执行:
cucumber.execution.order=defined
这样无论测试怎么触发,都会严格遵循你写的场景顺序,确保添加操作在前,删除操作在后。
方案二:合并连贯场景(推荐)
因为添加和删除本来是连贯的流程,可以将两个Scenario合并为一个,用Background复用重复的登录步骤,从根源上避免顺序问题:
@Events @ExhPlanFlow Feature: Insert and delete an Exh Plan Background: Given I login as admin Scenario: Insert then delete an ExhPlan And I go to automated test When I go to ExhPlan section And Insert a new exh plan Then The exh plan is listed And Open the automatized tests edition When I go to the exh plan section And The new exh plan is deleted Then The new exhibitor plan is deleted
方案三:标签依赖(耦合性较高)
如果必须分开两个Scenario,可以通过标签配合Hook实现依赖检查。比如在删除场景的@Before钩子中,验证添加场景是否已执行,若未执行则自动触发添加步骤:
@Before("@DeleteExhPlan") public void ensureExhPlanExists() { // 这里可以检查是否已存在新增的ExhPlan,若不存在则执行添加步骤的逻辑 // 注意:这种方式会让Hook和业务步骤耦合,不推荐大规模使用 }
内容的提问来源于stack exchange,提问作者Pedro Santangelo
相关产品推荐
相关产品推荐

