There is a really good exchange on Programmers Stack Exchange on the number of assertions to have in a single unit test: Is it OK to have multiple asserts in a single unit test?
Proper unit tests should fail for exactly one reason, that's why you should be using one assert per unit test.
The "match at least one" example below relies on Hamcrest matchers. There is an alternative to Hamcrest, see AssertJ documentation.
@Test
public void testMatchThisOrThat() {
// What if the result is either one or two?
// Gotcha' covered! :)
// Remember to import static org.hamcrest.CoreMatchers.* so the matchers come into scope.
assertThat(dataType, anyOf(is("one"), is("two")));
}
In this next case, I had an array of values where one or more elements should be matched. The Hamcrest IsIn
matcher seems like a good fit, e.g.
@Test
public void testMatchIsIn() {
// The result should be one of an array value.
assertThat(dataType, isIn(new String[]{"one","two","three"}));
}
Note: This requires the Hamcrest library.
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
</dependency>
@Test(expected = IndexOutOfBoundsException.class)
public void empty() {
new ArrayList<Object>().get(0);
}
@Test
public void testExceptionMessage() {
try {
new ArrayList<Object>().get(0);
fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
}
}
See Expected Exceptions.