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

SpringBoot项目Cucumber测试执行失败,能否用JUnit 5解决?

解决JUnit4版本的"Test events were not found"问题

1. 修正测试类可见性

你的CucumberIntegrationTest是包私有类(默认class修饰符),Gradle和JUnit无法扫描到非public的测试类,需改为public;同时glue路径要包含CucumberIntegrationConfiguration所在的包,否则Spring上下文无法被Cucumber加载:

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources/features/Dummy.feature",
        glue = {"com.chrispie.steps", "com.chrispie.config"}) // 添加上下文配置类所在包
public class CucumberIntegrationTest {}

2. 调整Gradle依赖与配置

如果SpringBoot默认引入了JUnit5,需显式添加JUnit4依赖避免冲突,并确保test任务能识别JUnit4测试:

dependencies {
    testImplementation 'io.cucumber:cucumber-java:7.20.1'
    testImplementation 'io.cucumber:cucumber-junit:7.20.1'
    testImplementation 'io.cucumber:cucumber-spring:7.20.1'
    // 显式引入JUnit4及兼容引擎
    testImplementation 'junit:junit:4.13.2'
    testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.9.2'
}

test {
    useJUnitPlatform() // 兼容JUnit4和JUnit5测试
    include '**/*CucumberIntegrationTest.class'
}

3. 验证文件路径

确认src/test/resources/features/Dummy.feature路径正确,且feature文件无语法错误。


切换到JUnit5实现(推荐)

Cucumber 7.x完全支持JUnit5,步骤如下:

1. 更新依赖

替换cucumber-junit为JUnit5平台引擎依赖:

dependencies {
    testImplementation 'io.cucumber:cucumber-java:7.20.1'
    // 替换为JUnit5平台引擎
    testImplementation 'io.cucumber:cucumber-junit-platform-engine:7.20.1'
    testImplementation 'io.cucumber:cucumber-spring:7.20.1'
    // SpringBoot自带JUnit5,无需额外引入
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

2. 修改测试类

移除@RunWith(Cucumber.class),改用JUnit5的@Cucumber注解:

@Cucumber
@CucumberOptions(
        features = "src/test/resources/features/Dummy.feature",
        glue = {"com.chrispie.steps", "com.chrispie.config"})
public class CucumberIntegrationTest {}

3. 确认Gradle配置

SpringBoot默认已配置JUnit平台,确保test任务使用JUnitPlatform:

test {
    useJUnitPlatform()
}

4. 上下文配置类无需修改

CucumberIntegrationConfiguration的@SpringBootTest和@CucumberContextConfiguration注解在JUnit5环境下依然有效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:47:11