Testing with Hamcrest

When I build software one of the things that I need to consider is how to test what I’ve built. Testing gives me a safety net to add new features and to refactor existing code without breaking functionality. For having the basics covered, I use unit tests, and with frameworks such as JUnit we can get easily used to code like this:

assertEquals(expected, actual, message)

When using this code, semantics don’t help, and the question is always the same: what is the expectation, and what is the actual? I tend to swap them, and sometimes I see the test fail with wrong messages. These messages can misguide us or the developer who needs to do some maintenance work.

One of the approaches that we can use for fixing this issue is by using Hamcrest, a JUnit extension that provides a different way of reading our tests. Let’s replace the previous code with:

assertThat(actual, is(expected)) 

With this way of writing, we are stating the assertion, asssertThat whatever object or property we want to validate has an expected value.

The method is, is named a “matcher”, a specific snippet that allow us to build a readable assertion, such as the following ones.

assertThat(result.message, is(equalToIgnoringCase("EXPECTED")));
assertThat(result.message, allOf(containsString("aa"), containsString("bb")));
assertThat(result, hasItem(expected));

As we can see in the previous examples, we have equality modifers, we are able to group different assertions into one and we even have support for Collections.

With this way, we can have more expressive tests and less error prone. This is not something “new”, in fact, it was added to JUnit 4.4 (check out the original release notes) but it’s a different way of writing our tests in Java.

Which syntax do you use for your tests?

Autor: Roberto Luis Bisbé

Software Developer, Computer Engineer


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s