JUnit 4 Tutorial: Introcution (Hello World) - 2020
Java:
$ java -version java version "1.7.0_65" OpenJDK Runtime Environment (IcedTea 2.5.1) (7u65-2.5.1-4ubuntu1~0.14.04.2) OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)
JAVA_HOME
:
$ which javac /usr/bin/javac $ readlink -f /usr/bin/javac /usr/lib/jvm/java-7-openjdk-amd64/bin/javac
Add JAVA_HOME
and System path to ~/.bashrc
:
-
Set JAVA_HOME, using the path just before the
bin
folder:export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
-
Append Java compiler location to System Path:
export PATH=$PATH:$JAVA_HOME/bin/
Run shell:
source ~/.bashrc
Download latest version of JUnit jar file
from https://github.com/junit-team/junit/wiki/Download-and-Install.
At the time of writing this tutorial, 'junit-4.11.jar' is the latest stable version.
We need 'hamcrest-core-1.3.jar' as well.
Put them into ~/usr/local/JUNIT
.
Set the JUNIT_HOME
environment variable to point to the base directory location where JUNIT jar is stored:
export JUNIT_HOME=/usr/local/JUNIT
Set the CLASSPATH
environment variable to point to the JUNIT jar location:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit-4.11.jar export CLASSPATH=$CLASSPATH:$JUNIT_HOME/hamcrest-core-1.3.jar
We may need to give permission to those jar files:
sudo chmod +r *.jar
Run shell:
source ~/.bashrc
Create a java class file name TestJunit in ~/JUNIT/workspace
:
import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { @Test public void testString() { String str= "Junit, Hello world!" ; assertEquals("Junit, Hello world!",str); } }
Create a java class file name TestRunner in ~/JUNIT/workspace
to execute Test case(s)
import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
$ javac TestJunit.java TestRunner.java $ java TestRunner true
JUnit & Maven Tutorial
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization