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

使用Maven Surefire运行JUnit 5单个测试类时如何执行@Nested测试?

解决JUnit 5 @Nested测试在Maven Surefire单独运行时不执行的问题

这个问题我之前也碰到过,核心原因是你使用的maven-surefire-plugin 2.19.1版本和JUnit 5的@Nested特性兼容性不足——旧版本的Surefire插件在指定单个测试类运行时,不会递归扫描并执行嵌套类里的@Test方法。

解决方案:升级Maven Surefire插件版本

你只需要把surefire插件升级到2.22.0及以上版本,就能解决这个问题。这个版本开始,Surefire的JUnit Platform Provider已经能正确识别并执行指定测试类下的所有@Nested测试。

修改后的Maven配置如下:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <!-- 升级到2.22.0或更高稳定版 -->
      <version>2.22.0</version>
      <dependencies>
        <dependency>
          <groupId>org.junit.platform</groupId>
          <artifactId>junit-platform-surefire-provider</artifactId>
          <version>${org.junit.platform.version}</version>
        </dependency>
        <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-engine</artifactId>
          <version>${org.junit.version}</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

验证效果

修改配置后,再次执行你的命令:

mvn -Dtest=com.mycompany.test.MyTest surefire:test

现在你会看到MyTest里的顶层测试和NestedTests里的嵌套测试都被执行了。

补充说明

如果你因为某些原因暂时无法升级插件,也可以使用JUnit Platform的控制台启动器来运行测试,不过这种方式需要额外配置,升级Surefire插件是最直接省心的方案。另外,你的测试类写法是符合JUnit 5要求的(@Nested类为public,且包含@Test方法),所以不需要调整测试代码。

内容的提问来源于stack exchange,提问作者Mateusz Wierciński

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:52:32