如何动态调用Junits

How to dynamically invoke Junits

我有多个 junit.framework.TestCase 类 实例,其中包含各种测试用例。我想编写一个从这些实例运行特定测试用例的程序。

有没有办法动态调用junit测试,类似于java.lang.reflectAPI?[=11=中的invoke()方法]

尝试使用 @Category 注释 您可以对测试进行分类,然后使用 @Category@Category

的组合调用它们

您可以使用 JUnitCore 调用 Junit,如果您 运行 整个测试套件都使用 Maven 会更好,正如@SubOptimal 指出的那样。

    JUnitCore junit = new JUnitCore();
    Result result = junit.run(CommonConstantsUnitTest.class);

因为你想要实现的目标不是很清楚。在下面找到一些更一般的可能性。如果你使用的是 Maven,你可以

  1. 运行 具体测试

(更多 examples/possiblities 参见 maven-surefire-plugin: single-test

mvn -Dtest=YourClass* test
  1. 为特定的 JUnit 类别注释 类

(更多 examples/possiblities 参见 maven-surefire-plugin: JUnit_Categories

mvn test -Dgroups="your.test.group.Example"

编辑 对于 ivy 此 SO post how-to-run-all-junit-tests-in-a-category-suite-with-ant 可能有助于解决您的需求。