Writing Assertions for Arrays using Hamcrest and JUnit

In this post, I will show you how to write assertions for Arrays making use of the Hamcrest library when writing your JUnit testcases. The post provides some useful examples, and some important tips I’ve learned through experience.

Requirements

The following list defines the technologies and libraries I used to implement the sample code:

Multiple Posts

This will form part of a multi-part series on how to write assertions using Hamcrest and JUnit.

Introduction

Hamcrest is a framework that assists the writing of unit testcases in the Java programming language. The name Hamcrest is an anagram for “matchers”. Hamcrest is a library of matchers, which can be combined to create flexible expressions of intent in tests, thus allowing ‘match’ rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock. Hamcrest has been included in JUnit 4 since 2012, but was omitted from Junit 5 in 2017.

Even though the assertion facilities provided by JUnit Jupiter are sufficient for many testing scenarios, there are times when more power and additional functionality such as matchers are desired or required. In such cases, the JUnit team recommends the use of third-party assertion libraries such as AssertJ, Hamcrest, Truth, etc. Developers are therefore free to use the assertion library of their choice. ~ JUnit 5 User Guide

Examples: Assertions for Arrays

This section contains a number of examples of how to make use of the Hamcrest Java Library to write assertions for Arrays as part of JUnit test cases. This is not suppose to be a complete list of all possible scenarios in which you can write assertions for Arrays, but serves as a list of frequently used examples.

Download Code

1. Assert that two Arrays are equal

A JUnit test method with an assertion that the two arrays are of the same length and contain items that are equal to each other.

@Test
public final void validateTwoArraysEqual() {
    String[] expectedResult = {"ABC", "DEF", "GHI"};
    String[] actualResult = {"ABC", "DEF", "GHI"};
   
    assertThat(actualResult, is(expectedResult));
    assertThat(actualResult, equalTo(expectedResult));
    assertThat(actualResult, is(equalTo(expectedResult)));
}

2. Assert that two Arrays are not equal

A JUnit test method with an assertion that the two arrays are not equal to each other.

@Test
public final void validateTwoArraysNotEqual() {
    String[] expectedResult = {"ABC", "DEF", "GHI"};
    String[] actualResult = {"AAA", "BBB", "CCC"};
   
    assertThat(actualResult, is(not(expectedResult)));
}

3. Assert that an Array is null

A JUnit test method with an assertion that Array is null.

@Test
public final void validateArrayNullValue() {
    String[] actualResult = null;
   
    assertThat(actualResult, is(nullValue()));
}

4. Assert that an Array is not null

A JUnit test method with an assertion that Array is not null.

@Test
public final void validateArrayNotNullValue() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
   
    assertThat(actualResult, is(notNullValue()));
}

5. Assert that an Array is empty

A JUnit test method with an assertion that matches when the length of the array is zero.

@Test
public final void validateArrayIsEmpty() {
    String[] actualResult = {};     
    assertThat(actualResult, emptyArray());
}

6. Assert that an Array is specific length or size

A JUnit test method with an assertion that matches when the length of the array equals the specified size.

@Test
public final void validateArraySizeLength() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
		
    assertThat(actualResult, arrayWithSize(3));
    assertThat(actualResult, arrayWithSize(equalTo(3)));
}

7. Assert that an Array contains a set of values

A JUnit test method with an assertion that matches when each item in the examined array is logically equal to the corresponding item in the specified items.

@Test
public final void validateArrayContains() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String[] expectedResult = {"ABC", "DEF", "GHI"};
        
    assertThat(actualResult, arrayContaining(expectedResult));
    assertThat(actualResult, arrayContaining(equalTo("ABC"), not(equalTo("AAA")), equalTo("GHI")));
    assertThat(actualResult, arrayContaining(Arrays.asList(equalTo("ABC"), not(equalTo("AAA")), equalTo("GHI"))));
}

8. Assert that an Array contains a set of values in any order

A JUnit test method with an assertion that matches when each item in the examined array is logically equal to one item anywhere in the specified items.

@Test
public final void validateArrayContainsInAnyOrder() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String[] expectedResult = {"ABC", "DEF", "GHI"};
        
    assertThat(actualResult, arrayContainingInAnyOrder(expectedResult));
    assertThat(actualResult, arrayContainingInAnyOrder(equalTo("ABC"), equalTo("DEF"), equalTo("GHI")));
    assertThat(actualResult, arrayContainingInAnyOrder(Arrays.asList(equalTo("ABC"), equalTo("DEF"), equalTo("GHI"))));
}

9. Assert that an Array contains a value

A JUnit test method with an assertion that matches when the examined array contains at least one item that is matched by the specified value.

@Test
public final void validateArrayHasItemInArray() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
        
    assertThat(actualResult, hasItemInArray("ABC"));
    assertThat(actualResult, hasItemInArray(startsWith(("A"))));
}

10. Assert that an Array is instance of type

A JUnit test method with an assertion that matches when the examined array is an instance of the specified type.

@Test
public final void validateArrayInstanceOfType() {
    String[] actualResult = {"ABC", "DEF", "GHI"};

    assertThat(actualResult, any(String[].class));
    assertThat(actualResult, isA(String[].class));
    assertThat(actualResult, instanceOf(String[].class));
}

11. Assert that an Array matches per item

A JUnit test method with an assertion that matches the number of matchers specified is equal to the length of the examined array.

@Test
public final void validateArrayItems() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
        
    assertThat(actualResult, is(array(equalTo("ABC"), equalTo("DEF"), equalTo("GHI"))));
} 

12. Combining Matchers using Both

A JUnit test method with an assertion that matches when both of the specified matchers match the examined object.

@Test
public final void validateBothArraysValues() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String expectedResult1 = "A";
    String expectedResult2 = "C";
        
    assertThat(actualResult[0], both(startsWith(expectedResult1)).and(endsWith(expectedResult2)));
} 

13. Combining Matchers using Either

A JUnit test method with an assertion that matches when either of the specified matchers match the examined object.

@Test
public final void validateEitherArrayValues() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String expectedResult1 = "A";
    String expectedResult2 = "C";
        
    assertThat(actualResult[0], either(startsWith(expectedResult1)).or(endsWith(expectedResult2)));
}

14. Combining Matchers using AllOf

A JUnit test method with an assertion that matches if the examined object matches ALL of the specified matchers.

@Test
public final void validateAllOfArraysValues() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String expectedResult1 = "A";
    String expectedResult2 = "C";
    String expectedResult3 = "B";
        
    assertThat(actualResult[0], allOf(startsWith(expectedResult1), endsWith(expectedResult2), containsString(expectedResult3)));
}

15. Combining Matchers using AnyOf

A JUnit test method with an assertion that matches if the examined object matches ANY of the specified matchers.

@Test
public final void validateAnyOfArraysValues() {
    String[] actualResult = {"ABC", "DEF", "GHI"};
    String expectedResult1 = "A";
    String expectedResult2 = "A";
    String expectedResult3 = "A";
        
    assertThat(actualResult[0], anyOf(startsWith(expectedResult1), endsWith(expectedResult2), containsString(expectedResult3)));
}

Summary

The examples listed in this post is not intended to be a complete list of how to make use of the Hamcrest Java Library to write assertions for Arrays. This post serves to illustrate some of the more frequent scenarios for writing assertions on Arrays. For more information and more examples, please follow me on any of the different social media platforms and feel free to leave comments.

Top