How to run JUnit tests on Mac terminal
How to run JUnit tests on Mac terminal
- 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.
- 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
:
- Edit two java files
JUnitDemo.java
andJUnitDemoTest.java
. Note that the names JUnitDemo.java and JUnitDemoTest.java must match. I store these two files in/Users/leslietang/Desktop/temp
:
- In directory
/Users/leslietang/Desktop/temp
, compile the file to be tested(i.e.,JUnitDemo.java
) using the commandjavac JUnitDemo.java
. Then compile the test file by commandjavac -cp .:/Users/leslietang/Desktop/junit_demo/junit-platform-console-standalone-1.5.2.jar JUnitDemoTest.java
:
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
.
- Run the tests by
java -jar /Users/leslietang/Desktop/junit_demo/junit-platform-console-standalone-1.5.2.jar --class-path . --scan-class-path
:
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:
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).