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

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

我可以使用以下方法在类中运行整套测试:

java -cp .... org.junit.runner.JUnitCore org.package.classname

我真正想做的是这样的:

java -cp .... org.junit.runner.JUnitCore org.package.classname.method

或:

java -cp .... org.junit.runner.JUnitCore org.package.classname#method

我注意到可能有一些方法可以使用 JUnit 注释来完成这项工作,但是我不希望手工修改测试类的源代码(试图自动完成这项工作)。我也看到 Maven 可能有办法做到这一点,但如果可能的话,我希望避免依赖于 Maven。

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


我在寻找的关键点:

  • 从 JUnit 测试类运行单个测试的能力
  • 命令行(使用 JUnit)
  • 避免修改测试源
  • 避免使用其他工具
106902 次浏览

You can make a custom, barebones JUnit runner fairly easily. Here's one that will run a single test method in the form 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);
}
}

You can invoke it like this:

> java -cp path/to/testclasses:path/to/junit-4.8.2.jar SingleJUnitTestRunner
com.mycompany.product.MyTest#testB

After a quick look in the JUnit source I came to the same conclusion as you that JUnit does not support this natively. This has never been a problem for me since IDEs all have custom JUnit integrations that allow you to run the test method under the cursor, among other actions. I have never run JUnit tests from the command line directly; I have always let either the IDE or build tool (Ant, Maven) take care of it. Especially since the default CLI entry point (JUnitCore) doesn't produce any result output other than a non-zero exit code on test failure(s).

NOTE: for JUnit version >= 4.9 you need hamcrest library in classpath

I use Maven to build my project, and use SureFire maven plugin to run junit tests. Provided you have this setup, then you could do:

mvn -Dtest=GreatTestClass#testMethod test

In this example, we just run a test method named "testMethod" within Class "GreatTestClass".

For more details, check out http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

We used IntelliJ, and spent quite a bit of time trying to figure it out too.

Basically, it involves 2 steps:

Step 1: Compile the Test Class

% javac -cp .:"/Applications/IntelliJ IDEA 13 CE.app/Contents/lib/*" SetTest.java

Step 2: Run the Test

% java -cp .:"/Applications/IntelliJ IDEA 13 CE.app/Contents/lib/*" org.junit.runner.JUnitCore SetTest

The following command works fine.

mvn -Dtest=SqsConsumerTest -DfailIfNoTests=false test