How to run JUnit test cases from the command line

前端 未结 11 1573
花落未央
花落未央 2020-11-22 02:09

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

11条回答
  •  不思量自难忘°
    2020-11-22 02:35

    Maven way

    If you use Maven, you can run the following command to run all your test cases:

    mvn clean test
    

    Or you can run a particular test as below

    mvn clean test -Dtest=your.package.TestClassName
    mvn clean test -Dtest=your.package.TestClassName#particularMethod
    

    If you would like to see the stack trace (if any) in the console instead of report files in the target\surefire-reports folder, set the user property surefire.useFile to false. For example:

    mvn clean test -Dtest=your.package.TestClassName -Dsurefire.useFile=false
    

    Gradle way

    If you use Gradle, you can run the following command to run all your test cases:

    gradle test
    

    Or you can run a particular test as below

    gradle test --tests your.package.TestClassName
    gradle test --tests your.package.TestClassName.particularMethod
    

    If you would like more information, you can consider options such as --stacktrace, or --info, or --debug.

    For example, when you run Gradle with the info logging level --info, it will show you the result of each test while they are running. If there is any exception, it will show you the stack trace, pointing out what the problem is.

    gradle test --info
    

    If you would like to see the overall test results, you can open the report in the browser, for example (Open it using Google Chrome in Ubuntu):

    google-chrome build/reports/tests/index.html
    

    Ant way

    Once you set up your Ant build file build.xml, you can run your JUnit test cases from the command line as below:

    ant -f build.xml 
    

    You can follow the link below to read more about how to configure JUnit tests in the Ant build file: https://ant.apache.org/manual/Tasks/junit.html

    Normal way

    If you do not use Maven, or Gradle or Ant, you can follow the following way:

    First of all, you need to compile your test cases. For example (in Linux):

    javac -d /absolute/path/for/compiled/classes -cp /absolute/path/to/junit-4.12.jar /absolute/path/to/TestClassName.java
    

    Then run your test cases. For example:

    java -cp /absolute/path/for/compiled/classes:/absolute/path/to/junit-4.12.jar:/absolute/path/to/hamcrest-core-1.3.jar org.junit.runner.JUnitCore your.package.TestClassName
    

提交回复
热议问题