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

> Test - Software, Framework and Library > Java - JUnit

1 - About

Steps on how to write a sample junit test.

Advertising

3 - Steps

3.1 - The source

Write a SimpleTest.java 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:
    @Test
    public void testEmptyCollection() {
    Collection collection = new ArrayList();
    assertTrue(collection.isEmpty());
    }
 
    // 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[]) {
         org.junit.runner.JUnitCore.main("myPackage.SimpleTest");
    }
}

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\SimpleTest.java

3.3 - Run the test

from the console:

java org.junit.runner.JUnitCore <test class name>
  • Where the class name has the form of “com.xyz.MyTestSuite”

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)
Advertising

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(ClassLoader.java:631)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native 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