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

如何按指定顺序优先运行Cucumber测试与JUnit单元测试?

让Cucumber测试优先于JUnit单元测试运行的方法

方法1:拆分Maven命令分两次执行

直接通过两条独立的Maven命令按顺序执行,也可以用命令连接符让它们自动连续运行:

  • 单独执行Cucumber测试:
    mvn test -Dsurefire.includeJUnit5Engines=cucumber -Dcucumber.plugin=pretty -Dcucumber.features="path-to-my-feature"
    
  • 单独执行JUnit单元测试:
    mvn test -Dsurefire.includeJUnit5Engines=junit-jupiter -Dtest=MyTestClass
    
  • 合并成一条自动执行的命令:
    Windows系统:
    mvn test -Dsurefire.includeJUnit5Engines=cucumber -Dcucumber.plugin=pretty -Dcucumber.features="path-to-my-feature" && mvn test -Dsurefire.includeJUnit5Engines=junit-jupiter -Dtest=MyTestClass
    
    Linux/macOS系统:
    mvn test -Dsurefire.includeJUnit5Engines=cucumber -Dcucumber.plugin=pretty -Dcucumber.features="path-to-my-feature" && mvn test -Dsurefire.includeJUnit5Engines=junit-jupiter -Dtest=MyTestClass
    

方法2:配置Maven Surefire插件多执行阶段

在项目的pom.xml中配置Surefire插件的两个执行块,明确指定执行顺序,后续只需运行mvn test即可按预定顺序执行:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.2.5</version> <!-- 使用当前最新稳定版即可 -->
            <executions>
                <!-- 第一阶段:运行Cucumber测试 -->
                <execution>
                    <id>execute-cucumber</id>
                    <phase>test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                    <configuration>
                        <includeJUnit5Engines>cucumber</includeJUnit5Engines>
                        <systemPropertyVariables>
                            <cucumber.plugin>pretty</cucumber.plugin>
                            <cucumber.features>path-to-my-feature</cucumber.features>
                        </systemPropertyVariables>
                    </configuration>
                </execution>
                <!-- 第二阶段:运行指定JUnit单元测试 -->
                <execution>
                    <id>execute-junit</id>
                    <phase>test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                    <configuration>
                        <includeJUnit5Engines>junit-jupiter</includeJUnit5Engines>
                        <includes>
                            <include>**/MyTestClass.java</include>
                        </includes>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

方法3:尝试JUnit 5的@Order注解(可靠性较低)

给JUnit测试类添加@Order(2),给Cucumber对应的步骤类添加@Order(1),但由于两者属于不同测试引擎,该注解的跨引擎顺序支持并不稳定,仅作为备选方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:14:55