Java - Junit - How do I write and run a simple test?

1 - About

Steps on how to write a sample junit test.

3 - Steps

3.1 - The source

Write a file

package myPackage;
import org.junit.*;
import static org.junit.Assert.*;

import java.util.*;
public class SimpleTest {

    // Write a test method (annotated with @Test) that asserts expected results on the object under test:
    public void testEmptyCollection() {
    Collection collection = new ArrayList();
    // Write a main method only if:
    //     - you don't want to give the runner in the command line and 
    //     - you want your class to be self-executable.
    public static void main(String args[]) {

3.2 - Compilation

To compile your JUnit tests, you'll need the following elements in your CLASSPATH:

  • The directory root of your class (original class files and test classes)
  • Libraries your class files depend on

set CLASSPATH=%CLASSPATH%;C:\temp\class\junit-4.8.1.jar;C:\myTestRootDirectory
javac myPackage\

3.3 - Run the test

from the console:

java org.junit.runner.JUnitCore <test class name>

  • Where the class name has the form of “”

Example with a testrunner:

java org.junit.runner.JUnitCore myPackage.SimpleTest
JUnit version 4.8.1
Time: 0,006

OK (1 test)

Example with the test runner in the main() method:

java myPackage/SimpleTest
JUnit version 4.8.1
Time: 0,007

OK (1 test)

4 - Support

4.1 - java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

D:\svn\Java\Snippet\src\junit>java org.junit.runner.JUnitCore HelloWorld
JUnit version 4.8.2
Exception in thread "main" java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(
        at java.lang.ClassLoader.defineClass(
        at Method)

Just add the org.harmcrest library in your classpath. From Eclipse: ECLIPSE_HOME\plugins\org.hamcrest.core_1.1.0.v20090501071000.jar

4.2 - Could not find class: junit/HelloWorld

java org.junit.runner.JUnitCore junit/HelloWorld
JUnit version 4.8.2
Could not find class: junit/HelloWorld

Time: 0.001

OK (0 tests)

The classpath is correct but the class can not be found. The solution: Use a point in the class name definition in place of a slash.

java org.junit.runner.JUnitCore junit.HelloWorld

5 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap