Skip to content

Assertions with assertThat

March 19, 2008

I like to think I’m reasonably up-to-date with Java technologies but then I discovered something today that shows up that I’m still ignorant of a lot of available technology that’s out there. Today I ran across hamcrest which is now apparently part of junit 4.4 and above.

Basically it replaces the old assertEquals() & variants with an assertThat statement. ie:


assertThat([value], [matcher statement]);

Some examples:


assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));

Basically all sorts of matchers are possible. The advantages here are improved failure reporting and a clearer expression of intent.

There’s some other interesting stuff built around this too – such as hamcrest collections. Take a look at this:


smiths = select(people, where(Person.class).getLastName(), equalToIgnoringCase("smith"));

Looks like good stuff to play around with over the next few days.

Advertisements

From → Testing

2 Comments
  1. I don’t perceive the claimed readability improvement. Could someone please clarify?

    When I get a failed test I don’t look for an error message, I go directly to the failing line, and I think the failed condition is obvious. Adding an error message is not worth learning another comparison language imho.

  2. Glen Stampoultzis permalink

    Well keep in mind I haven’t used this yet but when you do checks such as

    assertTrue( actual < 20 )

    you don't see what the value of 'actual' is – just that it failed. Sure you could fire up a debugger and rerun your test but this is a nice little bit of extra information.

    Now it could be that this still doesn't make the use of matchers worthwhile but I'll find that out after I play around a bit more. I'd be interested to hear from anyone who'd had some experience trying to use this (negative or positive).

Comments are closed.

%d bloggers like this: