by Rafał Borowiec

Menu

Sunday, July 14, 2013

To improve the readability of my unit tests I use assertThat with Hamcrest matchers. This is a good way to improve readability of your test code, especially when I statically import members of like org.junit.Assert.assertThat and org.hamcrest.Matchers. But when I add Mockito matchers on top of it, I experienced the problem of static import conflicts that ended up with "not nice" code (according to my definition).
Let's look at the (hypothetical) example:

In the assert section I must choose to statically import either org.hamcrest.Matchers.startsWith or org.mockito.Matchers.startsWith. And I don't really like it.
Then, some time ago, someone mentioned on Twitter that I should try FEST Fluent Assertions. So I gave it a try and I ended up with the below:

Of course, FEST Fluent Assertions is not about solving the static import problem - it also (or first of all) "provides a fluent interface for assertions". And this is where the readability comes into play. Consider the below example: