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

Eclipse Oepe Junit Library


Steps on how to write a sample junit test.


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[]) {


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\

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)


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

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

Documentation / Reference

Discover More
Hudson Job Ant Junit
Hudson - Ant Build Steps with Junit Test Call

This article shows you an example on how you can start your junit test with the Ant builder (runner) and Hudson as Scheduler and reporter. An Hudson Job can call an Ant script. Ant can call junit...
Java Conceptuel Diagram

Why has become so popular among application developers? Primarily because makes application developers more productive. It is a modern, robust, object-oriented language. ’s unprecedented popularity...

Share this page:
Follow us:
Task Runner