You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Cucumber与TestNG单独执行指定Feature测试?

问题分析与修复方案

问题原因

Cucumber的核心机制是自动扫描所有带有@Given/@When/@Then等步骤注解的类,和TestNG suite.xml里指定的类无关。另外你当前的步骤类都继承了带@CucumberOptions的TestRunner,这会导致Cucumber启动时直接扫描所有步骤类,无视TestNG的类选择配置。


修复步骤

1. 调整类的继承关系

步骤类不需要继承TestRunner,TestRunner作为独立的测试入口类存在:

修改FirstSteps和SecondSteps,移除继承关系:

public class FirstSteps {

    @When("First Step")
    public void firstStep() {
        System.out.println("FirstSteps::firstStep");
    }

    @Then("Second Step")
    public void secondStep() {
        System.out.println("FirstSteps::secondStep");
    }
}

public class SecondSteps {
    @When("First Function")
    public void firstFunction() throws InterruptedException {
        Thread.sleep(1000);
        System.out.println("SecondSteps::firstFunction ");
    }

    @Then("Second Function")
    public void secondFunction() {
        System.out.println("SecondSteps::secondFunction");
    }
}

TestRunner保持独立,可补充glue参数明确扫描范围:

@CucumberOptions(
        features = {"src/test/resources"},
        glue = {"com.projectname.tests.suites"} // 指定步骤类所在包
)
public class TestRunner extends AbstractTestNGCucumberTests {
}

2. 修改smoke.xml,指定运行TestRunner

Cucumber和TestNG的集成入口是TestRunner,而非步骤类。修改suite.xml指向TestRunner:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Test Debug">
    <test name="Test 1">
        <classes>
            <class name="com.projectname.tests.suites.TestRunner"/>
        </classes>
    </test>
</suite>

3. 控制仅运行指定步骤/Feature

如果只想执行FirstSteps对应的场景,有两种常用方式:

  • 标签过滤:给feature文件中的目标场景加标签,比如@smoke:

    @smoke
    Scenario: 第一个测试场景
      When First Step
      Then Second Step
    

    然后在TestRunner的@CucumberOptions中指定标签:

    @CucumberOptions(
            features = {"src/test/resources"},
            glue = {"com.projectname.tests.suites"},
            tags = "@smoke"
    )
    
  • 指定Feature文件:直接在@CucumberOptions中指定要运行的feature文件路径:

    @CucumberOptions(
            features = {"src/test/resources/first_scenario.feature"}, // 替换为你的实际文件路径
            glue = {"com.projectname.tests.suites"}
    )
    

4. 验证执行结果

重新执行命令:

mvn clean test -DsuiteXmlFile="src/test/resources/suites/smoke.xml"

此时只会运行你指定的目标步骤,不会执行SecondSteps中的内容。

内容的提问来源于stack exchange,提问作者hhrzc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:05:26