How to run JUnit test cases from the command line

2018-12-31 06:31发布

I would like to run JUnit test cases from the command line. How can I do this?

11条回答
忆尘夕之涩
2楼-- · 2018-12-31 07:01

Personally I would use the Maven surefire JUnit runner to do that.

查看更多
怪性笑人.
3楼-- · 2018-12-31 07:01

Alternatively you can use the following methods in JunitCore class http://junit.sourceforge.net/javadoc/org/junit/runner/JUnitCore.html

run (with Request , Class classes and Runner) or runClasses from your java file.

查看更多
低头抚发
4楼-- · 2018-12-31 07:02

Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar

查看更多
旧时光的记忆
5楼-- · 2018-12-31 07:03

For JUnit 5.x it's:

java -jar junit-platform-console-standalone-<version>.jar <Options>

Find a brief summary at https://stackoverflow.com/a/52373592/1431016 and full details at https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher

For JUnit 4.X it's really:

java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

But if you are using JUnit 3.X note the class name is different:

java -cp .:/usr/share/java/junit.jar junit.textui.TestRunner [test class name]

You might need to add more JARs or directories with your class files to the classpath and separate that with semicolons (Windows) or colons (UNIX/Linux). It depends on your environment.

Edit: I've added current directory as an example. Depends on your environment and how you build your application (can be bin/ or build/ or even my_application.jar etc). Note Java 6+ does support globs in classpath, you can do:

java -cp lib/*.jar:/usr/share/java/junit.jar ...

Hope it helps. Write tests! :-)

查看更多
高级女魔头
6楼-- · 2018-12-31 07:04

In windows it is

java -cp .;/path/junit.jar org.junit.runner.JUnitCore TestClass [test class name without .class extension]

for example: c:\>java -cp .;f:/libraries/junit-4.8.2 org.junit.runner.JUnitCore TestSample1 TestSample2 ... and so on, if one has more than one test classes.

-cp stands for class path and the dot (.) represents the existing classpath while semi colon (;) appends the additional given jar to the classpath , as in above example junit-4.8.2 is now available in classpath to execute JUnitCore class that here we have used to execute our test classes.

Above command line statement helps you to execute junit (version 4+) tests from command prompt(i-e MSDos).

Note: JUnitCore is a facade to execute junit tests, this facade is included in 4+ versions of junit.

查看更多
登录 后发表回答