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

在Cucumber中使用Selenide软断言时ErrorsCollector配置方法问询

Cucumber + Selenide 软断言配置方案

配置原理说明

Cucumber的场景生命周期未适配Selenide默认绑定JUnit/TestNG的软断言机制,因此直接开启assertionMode = SOFT会触发配置错误,确实需要通过Hooks的前后置方法手动管理ErrorsCollector实现软断言能力。

具体配置步骤

你可以直接在现有Hooks类中新增如下配置:

  1. 在Hooks类中声明非静态的ErrorsCollector实例
import com.codeborne.selenide.assertions.SoftAssertions;
import com.codeborne.selenide.logevents.SelenideLogger;
import io.cucumber.java.Before;
import io.cucumber.java.After;
import io.cucumber.java.Scenario;

private SoftAssertions errorsCollector;
  1. 在现有@Before方法中初始化收集器并绑定监听器,和你现有的Selenide配置放在一起即可
@Before
public void beforeScenario(Scenario scenario) {
  // 原有Selenide驱动、基础配置逻辑保留
  Configuration.assertionMode = AssertionMode.SOFT;
  // 新增软断言收集器配置
  errorsCollector = new SoftAssertions();
  SelenideLogger.addListener("softAssertListener", errorsCollector);
}
  1. 新增@After方法处理软断言结果并清理资源
@After
public void afterScenario(Scenario scenario) {
  try {
    // 汇总当前场景所有软断言失败项
    errorsCollector.assertAll();
  } catch (AssertionError allSoftErrors) {
    // 将错误信息写入Cucumber报告
    scenario.log("软断言失败汇总:" + allSoftErrors.getMessage());
    scenario.fail(allSoftErrors);
  } finally {
    // *必须移除监听器,避免多场景运行时错误数据污染*
    SelenideLogger.removeListener("softAssertListener");
  }
}

其他需要调整的配置项

  • 不要在全局静态代码块中设置Configuration.assertionMode = SOFT,统一放在@Before方法中按场景设置,避免多线程并行执行时配置串扰
  • 不要将errorsCollector声明为静态变量,每个场景需要独立的收集器实例
  • 如果使用JUnit平台启动Cucumber,不要同时引入Selenide提供的SoftAssertExtension等JUnit扩展,会和手动配置的收集器产生冲突
  • Selenide 6.0+版本才将SoftAssertions归入com.codeborne.selenide.assertions包,低版本需要对应调整导入路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:06:06