Custom Assertions in FEST Assert

I used to write the following code quite often in my unit tests:

assertEquals(2, list.size());
assertTrue(list.contains(element1));
assertTrue(list.contains(element2));

In order to reduce duplication these three lines of code can be extracted to a custom assertion:

assertContainsOnlyTheseElements(list, element1, element2)

Instead of writing your own assertions you can use the FEST Assert library. This is how you can express it in FEST:

assertThat(list).hasSize(2).contains(element1, element2);

Or even better:

assertThat(list).containsExactly(element1, element2);

Isn’t it beautiful? It reads almost like a natural language.

It’s also very easy to use because it requires only a single static import from org.fest.assertions.Assertions. The assertThat method is overloaded for multiple different types, each with specific assertions. The error messages in case of assertion failure are also quite user-friendly. For these reasons I prefer to use FEST Assert over Hamcrest for custom assertions.

Share
This entry was posted in Java and tagged , , . Bookmark the permalink.

3 Responses to Custom Assertions in FEST Assert

  1. mP says:

    What about a few examples between a Hamcrest and Fest assertion messages.

  2. Good point. I only mentioned that I prefer Fest over Hamcrest but it’s good idea to write a post with detailed comparison. Thanks!

  3. Pingback: A Cool Technique for Object Comparison in JUnit | Piotr Jagielski's Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>