Matching a Group of Map Properties from Any Map within a List

Let’s say that you have an ArrayList of LinkedHashMaps. Let’s further say that you would like to find any Map within that List, which contains a set of Properties. Here is how you can write a Unit Test with Hamcrest Matchers to do this:


import org.hamcrest.Matchers;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import java.util.LinkedHashMap;
import java.util.List;

public class MyTest{
	@Test
	public void testListOfMap() {
		List<LinkedHashMap<String, Object>> responseList = (List<LinkedHashMap<String, Object>>) getResponse();

		assertThat(responseList,
		Matchers.hasItem(Matchers.<LinkedHashMap<String, Object>>allOf(hasEntry("ticker", "PGRNX"),
		hasEntry("cusip", "704223783"), hasEntry("name", "Pax Global Environmental Mrkts"),
		hasEntry("scale", 3), hasEntry("closed", false))));

		assertThat(responseList,
		Matchers.hasItem(Matchers.<LinkedHashMap<String, Object>>allOf(hasEntry("ticker", "VTIAX"),
		hasEntry("cusip", "921909818"), hasEntry("name", "Vanguard Total Intl Stock Index Admiral"),
		hasEntry("scale", 3), hasEntry("closed", false))));
	}
}

Here we can see that we are checking that the list contains two Maps. Each time we are looking for a Map that matches on five different key-value pairs, such as “ticker”, “cusp”, “name”, “scale” and “closed”. Here you can see we are checking a variety of data types like String, Integer, and Boolean. As a result, we must properly parameterize the Matcher “allOf”; otherwise, we would see the following compilation error:

 

The method allOf(Matcher<? super T>, Matcher<? super T>, Matcher<? super T>, Matcher<? super T>, Matcher<? super T>) in the type Matchers is not applicable for the arguments (Matcher<Map<? extends String,? extends String>>, Matcher<Map<? extends String,? extends String>>, Matcher<Map<? extends String,? extends String>>, Matcher<Map<? extends String,? extends Integer>>, Matcher<Map<? extends String,? extends Boolean>>)

We use “allOf” to make sure that all five properties match on a given Map. We use the Matcher “hasItem”, because we want to find at least one Map that meets the criteria of matching on all five properties. We do not use the “contains” Matcher, because that would check that every Map meets has all five of the properties matching.

Leave a Reply

Your email address will not be published. Required fields are marked *