JUnit4’s advanced features

In our Spring 2.5 flagship project, we have chosen to use JUnit 4 and its constraint-based asserts. This is similar to how you write mock objects using the jMock library.

In short, the assertions take form of assertThat(T t, Constraint<T>). The Constraint<T> is an interface that the framework calls to validate the value t.

To get started, download JUnit (4.4) and jMock, unzip the downloaded file and jump straight into writing a test.


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

public class InvoiceTest {

    @Test public void testAddLine() {
        Invoice invoice = new Invoice();
        InvoiceLine line = new InvoiceLine();
        invoice.addLine(line);
        assertThat(line, org.hamcrest.collection.IsIn.isIn(invoice.getLines()));
    }

}

So here you have it. Your first test using JUnit jMock-style constraints rather than TestCase.assertXXX calls.

Leave a Reply