Sometime back I wrote about some testing anti-patterns. Recently I came back to the project and made some trivial changes. I fixed a bug upgraded spring and junit and migrated the test assertions to hamcrest fluid style. The full project is available on git.
I find hamcrest to be a much cleaner way of writing assertions. This test demonstrates the use of its fluid interface with some simple collection assertions. There are newer versions of Hamcrest and the collection package may have moved into core, but the version I use here (1.0) was available on maven. Note the integration with Junit. The hasItem and hasItems methods are sourced from Junit 4.8.1.
package org.testpatterns.hamcrestexamples;
import java.util.Arrays;
import org.junit.Test;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.junit.matchers.JUnitMatchers.*;
import static org.junit.Assert.assertThat;
public class CollectionExamples {
//Hamcrest with Collections and Arrays:
static final String[] array = { "A", "B", "C" };
static final List<String> list = Arrays.asList(array);
@Test
public void oneThingInArray () {
assertThat(array, hasItemInArray("A"));
}
@Test
public void arrayOfItemsInList () {
String[] expected = { "A", "B", "C" };
assertThat(list, hasItems(expected));
}
@Test
public void itemInAList () {
assertThat(list, hasItem("A"));
}
@Test
public void itemsInAList () {
assertThat(list, hasItems("A", "C"));
}
}













