Syntactic Sugar with Hamcrest

Do you love sugar? Syntactic Sugar? If you do then you would like Hamcrest. Hamcrest makes unit tests little more readable.

The following is a simple JUnit test:

   1: @Test
   2: public void SimpleBoolean() {
   3:     assertEquals(true, coolTest());        
   4: }

Now, using Hamcrest:

   1: @Test
   2: public void SimpleBoolean_Hamcrest() {
   3:     assertThat(coolTest(), is(true));
   4: }

Notice the usage of static imports in both the versions. Also, in the Hamcrest version the actual and expected are switched. Some people think that the Hamcrest version is more natural. Is this syntactic sugar worth it? To help you decide checkout the following additional example:

   1: @Test
   2: public void Comparison() {
   3:     assertEquals(true, commission() > 10);
   4: }

The Hamcrest version is:

   1: @Test
   2: public void Comparison_Hamcrest() {
   3:     assertThat(commission(), is(greaterThan(10)));
   4: }

The following is an example of comparing BigDecimals. Usually, code like this is pretty ugly.

   1: @Test
   2: public void CompareBigDecimal() {
   3:     assertEquals(true, new BigDecimal("0.99").compareTo(price()) == 0);
   4: }

And the Hamcrest version:

Note: Just ordering comparison was added in the later version of Hamcrest.

   1: @Test
   2: public void CompareBigDecimal_Hamcrest() {
   3:     assertThat(price(), comparesEqualTo(new BigDecimal("0.99")));
   4: }

I have seen code that uses Hamcrest assertThat as assertEquals, but I think that defeats the purpose. In this case, may be the developer is missing the point of syntactic sugar?

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name (required)

 Email (will not be published) (required)

 Website

Your comment is 0 characters limited to 3000 characters.