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

能否为Cucumber报告添加自定义CSS样式的多类型文本?

在Cucumber报告中添加自定义CSS样式的文本

当然可以实现!Cucumber的Scenario.write()方法其实支持插入HTML内容,这就给了我们自定义文本样式的空间。下面是具体的实现步骤:

1. 修改步骤定义,插入带自定义类的HTML文本

你只需要把要展示的文本用HTML标签包裹,并添加自定义的CSS类,替代原来的纯文本写法:

import cucumber.api.Scenario;
public class MyStepdefs {
    private Scenario scenario;
    @Before
    public void before(Scenario scenario) {
        this.scenario = scenario;
    }
    @Given("^I print a text in Cucumber report$")
    public void print() {
        // 信息类型A:蓝色背景的提示文本
        scenario.write("<div class='info-type-a'>这是信息类型A的自定义样式文本</div>");
        // 信息类型B:橙色背景的警示文本
        scenario.write("<div class='info-type-b'>这是信息类型B的自定义样式文本</div>");
        // 保留原有普通文本(会使用默认的embedded-text样式)
        scenario.write("This goes into the report(s)\n");
    }
}

2. 添加自定义CSS样式

接下来需要把你的自定义样式添加到Cucumber报告的样式文件中:

针对默认Cucumber HTML报告

如果使用的是Cucumber-JVM自带的HTML报告插件,你可以:

  • 在项目的src/test/resources目录下创建cucumber-html-reports文件夹
  • 新建一个CSS文件(比如custom-styles.css),写入你的自定义样式:
/* 信息类型A样式 */
.cucumber-report .step .info-type-a {
    background: #e3f2fd;
    color: #1565c0;
    padding: 8px;
    border-radius: 4px;
    margin: 4px 0;
}

/* 信息类型B样式 */
.cucumber-report .step .info-type-b {
    background: #fff3e0;
    color: #ef6c00;
    padding: 8px;
    border-radius: 4px;
    margin: 4px 0;
}

/* 保留默认的embedded-text样式(可选) */
.cucumber-report .step .embedded-text {
    background: #dddddd;
}
  • 然后在构建脚本中配置插件加载这个自定义样式(比如Maven的cucumber-reporting插件,可以通过customCss参数指定路径)

注意事项

  • 确保插入的HTML标签是闭合的,避免破坏报告的整体结构
  • 自定义类名尽量避免和Cucumber默认样式的类名冲突
  • 如果需要更复杂的样式,比如字体大小、边框等,都可以在CSS中自由定义

内容的提问来源于stack exchange,提问作者Stéphane GRILLON

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:29:06