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

SpringBoot 2.6.5集成Cucumber 7.3.8异常:场景不执行无Spring日志

SpringBoot 2.6.5 + Cucumber 7.3.8 无SpringBoot日志、测试场景不执行问题排查

核心问题定位与解决步骤

1. Cucumber未关联Spring上下文(最可能原因)

你的主测试类ApplicationTest的glue参数仅指定了step包,但CucumberSpringContextConfiguration所在的包未被纳入扫描范围,导致Cucumber完全没加载Spring上下文,自然不会输出Spring日志,也无法触发依赖Spring的测试逻辑。

解决:
修改@CucumberOptions的glue参数,添加上下文配置类所在包:

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"classpath:features"},
        glue = {"com.my.example.project.step", "com.my.example.project"}, // 添加上下文配置类所在的父包或具体包
        plugin = {"pretty","html:target/html-reports.htm"}
)
public class ApplicationTest {

}

如果配置类和step类在同一个父包下,直接用父包路径com.my.example.project即可覆盖所有需要扫描的类。

2. 日志配置缺失导致Spring日志被屏蔽

Cucumber默认使用自身日志配置,可能覆盖了SpringBoot的日志输出规则。需要在测试环境配置中显式开启Spring相关日志。

解决:
在src/test/resources/application-test.properties中添加日志配置:

# 开启Spring框架基础日志
logging.level.org.springframework=INFO
# 开启项目自身包的日志
logging.level.com.my.example.project=DEBUG

如果使用Logback,可在src/test/resources/logback-test.xml中添加对应日志输出节点。

3. 验证Spring上下文是否真正启动

在CucumberSpringContextConfiguration的init方法中添加日志打印,确认Spring上下文是否被加载:

@Before
public void init() {
    System.out.println("Spring上下文初始化完成,Resetable实例数量:" + CollectionUtils.emptyIfNull(resetables).size());
    CollectionUtils.emptyIfNull(resetables).stream().forEach(v -> v.reset());
}

运行测试后如果未看到该输出,说明glue路径仍未配置正确,Cucumber未扫描到配置类。

4. JUnit版本兼容性问题

Cucumber 7.x原生支持JUnit 5(Jupiter),但你使用的@RunWith(Cucumber.class)是JUnit 4的注解,可能和SpringBoot 2.6.x的JUnit 5环境冲突。

解决:
切换为Cucumber的JUnit 5支持:

  • 替换依赖(以Maven为例):
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.3.8</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-spring</artifactId>
    <version>7.3.8</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit-platform-engine</artifactId>
    <version>7.3.8</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-suite</artifactId>
    <version>1.9.1</version>
    <scope>test</scope>
</dependency>
  • 修改主测试类注解:
@Cucumber
@CucumberOptions(
        features = {"classpath:features"},
        glue = {"com.my.example.project.step", "com.my.example.project"},
        plugin = {"pretty","html:target/html-reports.htm"}
)
public class ApplicationTest {

}

额外验证步骤

  • 确认features目录下的.feature文件格式正确,场景步骤与step定义的方法完全匹配(关键字、参数一致);
  • 检查SpringTestConfig的组件扫描规则,确保Resetable接口的实现类未被错误排除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:40:16