This post originated from an RSS feed registered with Agile Buzz
by Joe Walnes.
Original Post: Flexible JUnit assertions with assertThat()
Feed Title: Joe's New Jelly
Feed URL: http://joe.truemesh.com/blog/index.rdf
Feed Description: The musings of a ThoughtWorker obsessed with Agile, XP, maintainability, Java, .NET, Ruby and OpenSource. Mmm'kay?
Over time I've found I end up with a gazillion permutation of assertion methods in JUnit: assertEquals, assertNotEquals, assertStringContains, assertArraysEqual, assertInRange, assertIn, etc.
Here's a nicer way. jMock contains a constraint library for specifying precise expectations on mocks that can be reused in your own assertion method (and that's the last time I'm going to mention mocks today, I promise - despite the frequent references to the jMock library).
By making a simple JUnit assertion method that takes a Constraint, it provides a replacement for all the other assert methods.
I call mine assertThat() because I think it reads well. Combined with the jMock syntactic sugar, you can use it like this:
Okay, that's nice but nothing radical. A bunch of assert methods have been replaced with different methods that return constraint objects. But there's more...
Combining constraints
Constraints can be chained making it possible to combine them in different permutations. For instance, for virtually every assertion I do, I usually find that I need to test the negative equivalent at some point:
junit.framework.AssertionFailedError:
Expected: (a string containing "color" or a string containing "colour")
but got : hello world
Implementing it
The simplest way is to grab jMock and create your own base test class that extends MockObjectTestCase. This brings in convenience methods for free (I'm still not talking about mocks, honest). If you don't want to extend this class, you can easily reimplement these methods yourself - it's no biggie.
import org.jmock.MockObjectTestCase;
import org.jmock.core.Constraint;
public abstract class MyTestCase extends MockObjectTestCase {
protected void assertThat(Object something, Constraint matches) {
if (!matches.eval(something)) {
StringBuffer message = new StringBuffer("\nExpected: ");
matches.describeTo(message);
message.append("\nbut got : ").append(something).append('\n');
fail(message.toString());
}
}
}
Now ensure all your test cases extend this instead of junit.framework.TestCase and you're done.
Defining custom constraints
Creating new constraints is easy. Let's say I want something like:
assertThat(something, between(10, 20));
To do that I need to create a method that returns a Constraint object, requiring two methods; eval() for performing the actual assertion, and describeTo() for the self describing error message. This is something that can live in the base test class.
public Constraint between(final int min, final int max) {
return new Constraint() {
public boolean eval(Object object) {
if (!object instanceof Integer) {
return false;
}
int value = ((Integer)object).intValue();
return value > min && value < max;
}
public StringBuffer describeTo(StringBuffer buffer) {
return buffer.append("an int between ").append(min).append(" and ").append(max);
}
}
}
This can be combined with other constraints and still generate decent failure messages.
Since using this one assert method I've found my tests to be much easier to understand because of lack of noise and I've spent a lot less time creating 'yet another assertion' method for specific cases. And in most cases I never need to write a custom failure message as the failures are self describing.