【问题标题】:Can you run all JUnit tests in a package from the command line without explicitly listing them?您可以在不显式列出的情况下从命令行运行包中的所有 JUnit 测试吗?
【发布时间】:2026-01-15 07:30:01
【问题描述】:

如果测试类和 JUnit 都在类路径中,可以从命令行运行 JUnit 测试,如下所示:

java org.junit.runner.JUnitCore TestClass1 TestClass2

现在,有没有办法同时在一个包(和子包)中运行所有测试?

我正在寻找类似的东西

java org.junit.runner.JUnitCore com.example.tests.testsIWantToRun.*

有没有简单的方法(不涉及 maven 或 ant)?

【问题讨论】:

  • 我想在持续集成服务器上运行一个包及其子包中的所有测试,但我不知道采用者会选择设置哪些包和测试。但我不能全部运行它们,因为某个包中的测试不应该在那个盒子上启动。因此,需要有人手动创建测试列表的任何事情都不理想(除非这样的列表可以完全包含排除项)。
  • 在得到初步答复后,我找到了自己问题的答案;它们与我下面的答案相关联。我也刚刚开始投票以将其作为重复项关闭。

标签: java unit-testing command-line junit


【解决方案1】:

Junit 允许您定义 suites 的测试。每个套件都定义了一组测试,运行套件会导致所有测试都运行。我所做的是为每个包定义一个套件,列出该包的测试类以及任何子包的套件:

package com.foo.bar;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import com.foo.bar.baz.Suite_baz;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    ThisTest.class,
    ThatTest.class,
    TheOtherTest.class,
    Suite_baz.class,
})
public class Suite_bar {
}

这并非完全轻松。您必须构建套件并使用新的测试类手动更新它们。我想如果有人愿意,编写一个小的 java 程序来自动生成这些并不难。

【讨论】:

    【解决方案2】:

    我问这个问题是为了能够有选择地在 Jenkins 上启动项目的 Cucumber 测试集,而无需真正知道它们的 RunTests 类将被称为什么、它们的 CucumberOptions 将包含什么或它们的位置。与此同时,我在 * 上发现了一些有用的线程,它们回答了我的问题:

    使用这些,我可以单独开始我的 Cucumber 测试,如下所示:

    首先,我使用 maven 程序集插件将测试打包到一个 jar 中: https://*.com/a/574650/2018047

    然后我将测试的依赖项复制到 Jenkins 上的目标文件夹中,如下所示: https://*.com/a/23986765/2018047

    我们已经有一个标志在设置时跳过我们的测试执行,所以我打包我的测试而不运行它们: mvn clean install -DskipMyTestModule=true

    并且使用上面的代码和下面的调用,我将能够使它全部工作......

    java -Dcucumber.options="src/test/resources/features --tags @b --format pretty:STDOUT --format html:target/cucumber-b --format json:target/cucumber-b.json" -Dname=value -cp target/artifact-1.2.8-SNAPSHOT-tests.jar;target/test-classes/libs/junit-4.11.jar;target/test-classes/libs/* org.junit.runner.JUnitCore com.example.foo.bar.test.cucumber.RunTest
    

    希望这对将来的某人有所帮助。 :)

    【讨论】:

      【解决方案3】:

      在 JUnit 4 中,使用一个名为 cpsuite 的扩展来支持这一点。您需要做的就是将它添加到您的测试类路径(maven io.takari.junit:takari-cpsuite),创建一个动态测试套件类:

      package com.mycompany;
      import org.junit.extensions.cpsuite.ClasspathSuite;
      import org.junit.runner.RunWith;
      
      @RunWith(ClasspathSuite.class)
      @ClasspathSuite.IncludeJars(true)
      public class RunAllTests {}
      

      并运行它:

      java -cp ${CP} org.junit.runner.JUnitCore com.mycompany.RunAllTests
      

      您的类路径 ${CP} 应包含您的测试 jar、junit、hamcrest 和 cpsuite。

      【讨论】:

        最近更新 更多