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

Cucumber JUnit转TestNG项目报错:无法实例化Cucumber运行类

解决Cucumber TestNG Runner类实例化失败的问题

你在从JUnit切换到TestNG的过程中,代码里残留了JUnit相关的配置,这正是导致org.testng.TestNGException: Cannot instantiate cucumber runner class错误的核心原因。下面一步步帮你修复:

核心问题分析

你的当前代码混合了JUnit的注解(@RunWith)和TestNG的runner类(AbstractTestNGCucumberTests),还导入了JUnit版本的Cucumber runner,这种混用会让TestNG无法正确识别并实例化runner类。

修复步骤

1. 清理JUnit相关代码

移除所有JUnit相关的导入和注解:

  • 删除import org.junit.runner.RunWith;
  • 删除import cucumber.api.junit.Cucumber;
  • 彻底移除@RunWith(Cucumber.class)注解

2. 编写正确的TestNG Runner类

你的runner类只需要继承AbstractTestNGCucumberTests并配置@CucumberOptions即可,示例代码如下:

package com.philips.rs.application.setup;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;

@CucumberOptions(
    features = "src/test/resources/features", // 替换为你的feature文件实际路径
    glue = "com.philips.rs.application.stepdefinitions", // 替换为你的步骤定义包路径
    format = {"pretty", "html:target/cucumber", "json:target/cucumber.json"}
)
public class TestNGCucumberRunner extends AbstractTestNGCucumberTests {
}

3. 确保依赖配置正确

确认你的构建工具(Maven/Gradle)中引入了cucumber-testng依赖,并且排除掉可能冲突的JUnit依赖:

Maven 依赖示例

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>7.14.0</version> <!-- 使用你项目对应的Cucumber版本 -->
    <scope>test</scope>
</dependency>
<!-- 若保留了cucumber-junit依赖,需排除JUnit核心依赖避免冲突 -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>7.14.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Gradle 依赖示例

testImplementation 'io.cucumber:cucumber-testng:7.14.0'
testImplementation('io.cucumber:cucumber-junit:7.14.0') {
    exclude group: 'junit', module: 'junit'
}

4. 验证运行

配置完成后,直接用TestNG运行这个runner类,就能正常执行Cucumber测试了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:52:22