Shaun Abram
Technology and Leadership Blog
AssertJ > Fest > Hamcrest
I have previously blogged about Hamcrest, and using its assertThat methods in preference to JUnit’s Assert.
However, I quickly after discovered FEST Assertions, and happily switched to it. It provides the same improved test readability and failure messages as Hamcrest, but has the extra benefit of enabling IDE auto completion, rather than having to search through package and class docs to find the right matcher.
Unfortunately, Fest seems to not longer be actively developed. The last stable release of the 1.x branch, 1.4, was released way back in 2011, and the new 2.x branch never made it to a stable release and hasn’t had a commit since June 2013.
Enter AssertJ…
Tags: assertj, fest, fluent, Hamcrest, JUnit
Hamcrest Matcher
As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.
An example usage could be:
String sql = "select a,b,c from tableA";
assertThat(sql, hasNumberOfSubstrings(",", 2));
See the source code below. I have been reading up on OSS licenses recently and decided to release this using the same license as Hamcrest – the new BSD license.
I have also attached a jar which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be downloaded as part of the hamcrest all-in-one jar.
Read more
Tags: Hamcrest, JUnit, Testing, unittesting
Hamcrest
Hamcrest is a framework for writing matcher objects. Matchers have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit’s assertEquals methods, we use Hamcrest’s assertThat construct with one (or more) of the many Matchers available. For example
assertTrue(a.equalTo(b));
becomes
assertThat(a, equalTo(b));
A small change in this example, but Hamcrest’s benefits are many, enabling you to write much more flexible tests that are easier to read and have more meaningful failure messages.
Read more