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

如何按指定标签顺序运行Karate测试用例?

Karate 1.4.1 按自定义标签优先级执行测试用例

问题场景

我有多个带有@run_first、@run_second、@run_third标签的Karate feature文件,示例如下:

文件m.feature:

Feature: test feature1
Background:
* print " test feature1"
@run_first
Scenario: run first feature test

文件a.feature:

Feature: test feature1
Background:
* print " test feature2"
@run_second
Scenario: run second feature test

当前测试默认按文件字母顺序执行,但需求是按标签优先级顺序执行:先运行所有带@run_first标签的用例,再执行@run_second的,最后处理@run_third的。使用Karate版本为1.4.1,需实现该执行顺序。

解决方案

方法1:Java测试类分批次执行

通过创建JUnit测试启动类,按顺序调用不同标签的测试任务,确保批次执行顺序。

JUnit 5 实现

import com.intuit.karate.junit5.Karate;

class TestSuite {

    @Karate.Test
    Karate executeRunFirst() {
        return Karate.run().tags("@run_first").relativeTo(getClass());
    }

    @Karate.Test
    Karate executeRunSecond() {
        return Karate.run().tags("@run_second").relativeTo(getClass());
    }

    @Karate.Test
    Karate executeRunThird() {
        return Karate.run().tags("@run_third").relativeTo(getClass());
    }
}

JUnit 5会严格按照测试方法的定义顺序执行,保证@run_first的用例全部完成后,再启动@run_second的任务,最后执行@run_third。

JUnit 4 实现

import com.intuit.karate.junit4.Karate;
import org.junit.Test;

public class TestSuite {

    @Test
    public void executeRunFirst() {
        Karate.run().tags("@run_first").relativeTo(getClass()).parallel(1);
    }

    @Test
    public void executeRunSecond() {
        Karate.run().tags("@run_second").relativeTo(getClass()).parallel(1);
    }

    @Test
    public void executeRunThird() {
        Karate.run().tags("@run_third").relativeTo(getClass()).parallel(1);
    }
}

这里需要将并行度设置为1,确保同一批次内的用例串行执行,且不同批次按方法定义的顺序依次执行。

方法2:命令行分阶段执行

如果需要通过构建工具(如Maven)或CI脚本控制执行顺序,可分三次执行命令:

# 执行所有@run_first标签的用例
mvn test -Dkarate.options="--tags @run_first"

# 执行所有@run_second标签的用例
mvn test -Dkarate.options="--tags @run_second"

# 执行所有@run_third标签的用例
mvn test -Dkarate.options="--tags @run_third"

按顺序执行这三条命令,即可实现标签优先级的执行顺序。

注意事项

  • 不要使用--tags @run_first,@run_second,@run_third这种逗号分隔的标签表达式,这种方式会把所有匹配的用例混合,仍按默认的文件字母顺序执行,无法保证批次优先级。
  • 若开启并行执行,同一批次内的用例会并行运行,但不同批次之间仍会按顺序执行,不影响整体优先级需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:45:19