Posts Tagged ‘junit’

JUnit’s clever assertEquals method

June 28, 2010 1 comment

I ran into a feature of JUnit the other day that is very useful, and a neat touch for the developers to put in; it really shows the authors’ attention to detail.

JUnit, for those uninitiated, is a unit testing framework for Java.  JUnit provides a set of statically available assertions you can invoke within your test cases in order to ensure that your software is behaving as you think it should.  They are accessible from the org.junit.Assert package and can be statically imported as follows:

import static org.junit.Assert.*;

This allows you to reference the methods without prefixing them with Assert; in other words you can call assertEquals(Object first, Object second) as opposed to Assert.assertEquals(Object first, Object second).

Anyways, JUnit provides a whole raft of assertEquals methods, overloaded for different types. I was pleasantly surprised to see that JUnit is clever enough to provide a ‘diff’ed output when the assertions fail. This makes it much easier to see where the failure occurred, as the difference in output is highlighted and obvious. Here are some examples:

import org.junit.Test;
import static org.junit.Assert.*;

public class AbsoluteTest {

    public void testStringAssertEquals() {

    public void testArrayAssertDifferingLengthEquals() {
        assertArrayEquals(new int[]{5,7,8,10},new int[]{5,7,8,9,10});

    public void testArrayAssertSameLengthEquals() {
        assertArrayEquals(new int[]{5,7,8,10},new int[]{5,7,8,9});


Here is the output:
Failed unit test output

Note that I used assertArrayEquals as opposed to assertEquals for the arrays; doing so compares arrays and their elements rather than just reference equality. Here is the same test with the method switched:

Unhelpful error messages

This is because the assertEquals method that takes two objects merely invokes the standard reference equality on the objects, and gives the toString representation of the arrays when they fail. Final little tip that relates to the previous point: if you ever need to print out the contents of an array in Java, Arrays.toString is your friend.

int[] array = {5,6,2,17,55};


[5, 6, 2, 17, 55]

The Arrays class has a lot of useful utility functions when working with arrays, including toString, and equals.

Categories: Java, UI, Uncategorized Tags: , , ,