How to create a Junit test

This tutorial shows how to create a simple Junit test in Java.

First it shows with the testBoolean method, how to test a boolean value using the assertTrue and assertFalse methods.

Then the testString method shows how to validate that a String is null, not null or that it is equal to a predefined value.

Finally, the method testNullException, show how to validate that a unit test throws a NullPointerException during the processing.

Create the following java file:

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
public class JunitSample {
    @Test
    public void testBoolean() {
        // Define a boolean
        boolean myBoolean = true;
        // Test if it's true
        assertTrue(myBoolean);
        // Test if it's false
        assertFalse(!myBoolean);
    }
    @Test
    public void testString() {
        // Define a null String
        String myString = null;
        // Test if it's null
        assertNull(myString);
        // Assign a value
        myString = "San Francisco";
        // Test if it's not null
        assertNotNull(myString);
        // Test if the value equals the "San Francisco" String
        assertEquals("San Francisco", myString);
    }
    /*
     * This test expects the test to return a NullPointerException
     */
    @Test(expected = NullPointerException.class)
    public void testNullException() {
        // Define a null thing
        String myString = null;
        // Throw a nullPointerException
        int pos = myString.indexOf("San Francisco");
    }
    public static void main(String[] argv) {
        // Define the core
        JUnitCore junit = new JUnitCore();
        // Run the test for the current class
        Result result = junit.run(JunitSample.class);
        // Write the results of the test in the output
        System.out.println("Test successful = " + result.wasSuccessful());
        System.out.println("Tests run = " + result.getRunCount());
        System.out.println("Test time = " + result.getRunTime() + " ms");
    }
}

The output will be:

	
Test successful = true
Tests run = 3
Test time = 8 ms
	

References:

Junit 4

Share this article:

Recent Comments