How to run JUnit test cases from the command line

前端 未结 11 1581
花落未央
花落未央 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:36

    If you project is ant based then you should be able to do something like this from the console:

    ant test
    

    If this doesn't work, but still your project is ant based, you can run ant -p to list the main targets of the project.

    0 讨论(0)
  • 2020-11-22 02:41

    If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:

    mvn clean test -pl :my-module -Dtest=CustomTest
    

    Or run only 1 test-method myMethod from test-class CustomTest using next command:

    mvn clean test -pl :my-module -Dtest=CustomTest#myMethod
    

    For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

    0 讨论(0)
  • 2020-11-22 02:43

    The answer that @lzap gave is a good solution. However, I would like to add that you should add . to the class path, so that your current directory is not left out, resulting in your own classes to be left out. This has happened to me on some platforms. So an updated version for JUnit 4.x would be:

    java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]
    
    0 讨论(0)
  • 2020-11-22 02:45

    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! :-)

    0 讨论(0)
  • 2020-11-22 02:48

    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.

    0 讨论(0)
提交回复
热议问题