How to run JUnit tests on Mac terminal

How to run JUnit tests on Mac terminal

  1. To run JUnit tests (in this case, JUnit5), firstly you need to download junit-platform-console-standalone-1.5.2.jar from Maven Central repository.

  1. After downloading the jar file, you can store it in a directory. As shown in the figure, I store it in /Users/leslietang/Desktop/junit_demo:

junit_test_1


  1. Edit two java files JUnitDemo.java and JUnitDemoTest.java. Note that the names JUnitDemo.java and JUnitDemoTest.java must match. I store these two files in /Users/leslietang/Desktop/temp:

junit_test_2


  1. In directory /Users/leslietang/Desktop/temp, compile the file to be tested(i.e., JUnitDemo.java) using the command javac JUnitDemo.java. Then compile the test file by command javac -cp .:/Users/leslietang/Desktop/junit_demo/junit-platform-console-standalone-1.5.2.jar JUnitDemoTest.java:

junit_test_3

Note that -cp can specify where to find user class files. We normally use this option when
our programs make use of class files that we’ve stored in a separate folder. In this case, when we compile JUnitDemoTest.java, we will use JUnitDemo.class(which is in current path .) and the class files in junit-platform-console-standalone-1.5.2.jar.


  1. Run the tests by java -jar /Users/leslietang/Desktop/junit_demo/junit-platform-console-standalone-1.5.2.jar --class-path . --scan-class-path:

junit_test_4

Here is the explanation of the commmand above: java -jar junit-platform-console-standalone-1.5.2.jar is to run JUnit Vintage, JUnit Jupiter tests and print test execution results to the console. --class-path . --scan-class-path means directories on the system classpath as well as additional classpath entries supplied via --class-path(directories and JAR files, in this case, the current path .) are scanned.


We also can use alias command to simplify the commands mentioned above, for example:

junit_test_5

Note that, the alias shown above command will only be available for your current terminal session. If you open new terminal session, the alias will no longer be available. To keep aliases between sessions, you can save them in your user’s shell configuration profile(~/.bashrc for Bash, ~/.zshrc for ZSH).