使用命令行从JUnit类运行单个测试

Kev*_*ert 91 java junit command-line unit-testing

我试图找到一种方法,允许我只使用命令行和java从JUnit类运行单个测试.

我可以使用以下方法从类中运行整个测试集:

java -cp .... org.junit.runner.JUnitCore org.package.classname
Run Code Online (Sandbox Code Playgroud)

我真正想做的是这样的事情:

java -cp .... org.junit.runner.JUnitCore org.package.classname.method
Run Code Online (Sandbox Code Playgroud)

要么:

java -cp .... org.junit.runner.JUnitCore org.package.classname#method
Run Code Online (Sandbox Code Playgroud)

我注意到有可能使用JUnit注释来实现这一点,但我宁愿不手动修改测试类的源代码(尝试自动化).我也看到Maven可能有办法做到这一点,但如果可能的话我想避免依赖Maven.

所以我想知道是否有办法做到这一点?


我正在寻找的要点:

  • 能够从JUnit测试类运行单个测试
  • 命令行(使用JUnit)
  • 避免修改测试源
  • 避免使用其他工具

Mar*_*ers 76

你可以很容易地制作一个定制的准系统JUnit跑步者.这是一个将在表单中运行单个测试方法的方法com.package.TestClass#methodName:

import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;

public class SingleJUnitTestRunner {
    public static void main(String... args) throws ClassNotFoundException {
        String[] classAndMethod = args[0].split("#");
        Request request = Request.method(Class.forName(classAndMethod[0]),
                classAndMethod[1]);

        Result result = new JUnitCore().run(request);
        System.exit(result.wasSuccessful() ? 0 : 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样调用它:

> java -cp path/to/testclasses:path/to/junit-4.8.2.jar SingleJUnitTestRunner 
    com.mycompany.product.MyTest#testB
Run Code Online (Sandbox Code Playgroud)

在快速查看JUnit源代码后,我得出的结论与JUnit本身不支持这一结论相同.这对我来说从来都不是问题,因为IDE都有自定义JUnit集成,允许您在游标下运行测试方法,以及其他操作.我从未直接从命令行运行JUnit测试; 我总是让IDE或构建工具(Ant,Maven)来处理它.特别是因为默认的CLI入口点(JUnitCore)在测试失败时不会产生除非零退出代码之外的任何结果输出.

注意:对于JUnit版本> = 4.9,您需要在类路径中使用hamcrest

  • 实际上,我似乎记得在测试中的断言失败时在日志中获得完整的堆栈跟踪,以及来自描述未实现期望的每个断言的(可选的,定义时的)消息.谢谢你的解决方案. (2认同)

Yil*_*ing 42

我使用Maven构建我的项目,并使用SureFire maven插件来运行junit测试.如果您有此设置,那么您可以这样做:

mvn -Dtest=GreatTestClass#testMethod test
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我们只在Class"GreatTestClass"中运行一个名为"testMethod"的测试方法.

有关更多详细信息,请查看http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html