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>]