Make Hamcrest to match a key or value in a Map

31 views
Skip to first unread message

albert kao

unread,
Feb 7, 2021, 10:00:39 AM2/7/21
to Hamcrest Java Users
I wrote this test program for Hamcrest and Map to use Hamcrest Matchers.
This program use Hamcrest as standalone (does not use JUnit).
Why none of the output is true (matched)?
How to modify this test program so that a key or value in a Map is matched (output is true)?

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.hamcrest.Matchers;
import org.hamcrest.collection.IsMapContaining;

public class TestMap {

public static void main(String[] args) {
Map<String, Integer> map = Stream.of(new Object[][] { 
{ "data1", 1 }, 
{ "data2", 2 }, 
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Matchers.hasKey(\"data1\") " + Matchers.hasKey("data1").matches("data1"));
System.out.println("Matchers.hasValue(1) " + Matchers.hasValue(1).matches(1));
System.out.println("IsMapContaining.hasKey(\"data1\") " + IsMapContaining.hasKey("data1").matches("data1"));
System.out.println("IsMapContaining.hasValue(1) " + IsMapContaining.hasValue(1).matches(1));
System.out.println("IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) " + IsMapContaining.hasEntry(entry.getKey(), entry.getValue()));
}
}
}

The output is:
Matchers.hasKey("data1") false
Matchers.hasValue(1) false
IsMapContaining.hasKey("data1") false
IsMapContaining.hasValue(1) false
IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) map containing ["data2"-><2>]
Matchers.hasKey("data1") false
Matchers.hasValue(1) false
IsMapContaining.hasKey("data1") false
IsMapContaining.hasValue(1) false
IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) map containing ["data1"-><1>]

Steve Freeman

unread,
Feb 14, 2021, 4:58:00 PM2/14/21
to Hamcrest Java Users
I’m not sure I understand your code, but it looks like you’re trying to match a value rather than a map.

For example, I think the first check should be 

System.out.println("Matchers.hasKey(\"data1\") " + Matchers.hasKey("data1").matches(map));

In practice this would be used as:

assertThat(map, hasKey(“data1”));

which is how it is intended to read.
Reply all
Reply to author
Forward
0 new messages