Using Junit from commandline

Published by moxlotus on

If you are someone who likes to use IDE/Gradle/Ant to run your JUnit tests, you probably will not be interested in using commandline. However, I am someone who really enjoys using the rudimentary tools to get the job done(I use Vim and Tmux for work). It is easy to find someone who knows how to use IDE/Gradle/Ant, but it is hard to find someone who knows how to do it without. So here I am going to show you how to do it without using any fancy tools - just JUnit and Java.

Junit 5

Let's clone the junit5 repository

$ git clone https://github.com/junit-team/junit5.git
$ cd junit5

Initialize the directory

./gradlew

Build from source

$ ./gradlew clean assemble

package the junit jar file (you may skip this if the jar file can be found after running the above step)

$ ./gradlew jar

The completed jar file for console launcher can be found here.

$ ls junit-platform-console-standalone/build/libs/junit-platform-console-standalone-1.7.0-SNAPSHOT-all.jar

set the jar file to an environment variable to avoid typing a long path string each time.

export CLASSPATH=~/junit5/junit-platform-console-standalone/build/libs/junit-platform-console-standalone-1.7.0-SNAPSHOT-all.jar

You may use the following sample test file - MoneyTest.java.

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class MoneyTest {

  @Test
  void testMultiplication() {
    assertEquals(2, 2);
  }

}

To run the test, we have to make sure the test file is compiled.

javac -cp .:$CLASSPATH MoneyTest.java

now we may use the test with junit5 scan the folder for all the available tests.

java -jar $CLASSPATH -cp . --scan-classpath

To just test a single method

java -jar $CLASSPATH -cp . -m MoneyTest#testMultiplication

Use the --help option to show you more options.

java -jar $CLASSPATH --help

Junit 4

Unlike Junit5 which we cloned the github repository, we will download 2 jar files to be used for Junit4.

  1. Junit4
  2. Hamcrest

We will need to set our environment variable to include the 2 jar files that we have just downloaded to be used in classpath.

export CLASSPATH=./junit/junit.jar:./junit/hamcrest.jar

same as Junit5, we will need to compile our test file

javac -cp .:$CLASSPATH MoneyTest.java

Use the following command to test using Junit4

java -cp .:$CLASSPATH org.junit.runner.JUnitCore MoneyTest
Share it with others
Categories: Java