Skip to main content

Writing Unit Tests

JUnit works by comparing expected output to actual output on your functions and object state. Here’s an example:

public class ExampleTest {

    @Test
    public void testSumFunction() {
        assertEquals("5 + 6 should be 11", 11, Example.sum(5, 6));
    }

}

We can also test to make sure an exception is thrown properly. Using the same setup as above:

   @Test(expected = IllegalArgumentException.class)
    public void testException() {
        SomeClass.readNonnullFile(null);
    }

You’ll find the following functions from the JUnit library useful:

assertTrue(someConditon);
assertFalse(someCondition);
assertEquals(expectedValue, actualValue);
assertEquals(expectedDouble, actualDouble, deltaValue);
assertArrayEquals(expectedArray, actualArray);

While you can put multiple assert statements in one test, you are encouraged to write tests with only one (or very few) assertions. With multiple assert statements in a test, if a single one of them fail, the whole test will fail and JUnit will only report one failure for one case. If you have your asserts separated into many different test functions, then you’ll be able to get a clearer total picture of your code’s correctness.

Running Unit Tests

To run your unit tests on Codio, navigate to Tools -> JUnit and then add all of the .java files containing your test cases in the field called “Add test case.” Then, press “Execute All” to run your selected tests.