JavaHamcrest icon indicating copy to clipboard operation
JavaHamcrest copied to clipboard

Added 'hasEntry' matchers for (key, valueMatcher) and (keyMatcher, value)

Open Shpota opened this issue 8 years ago • 7 comments

When I test maps I often need to apply a matcher for the value and check equality for the key. Currently there is no hasEntry matcher that consumes a key, and a matcher for the value so I have to do it somewhat like this:

Map<String, List<Integer>> map = singletonMap("key", asList(1, 2));

assertThat(map, hasEntry(equalTo("key"), contains(1, 2)));

It would be more convenient to do it like this:

assertThat(map, hasEntry("key", contains(1, 2)));

For that reason, I introduced two more hasEntry matchers with signatures:

hasEntry(K key, Matcher<? super V> valueMatcher)
hasEntry(Matcher<? super K> keyMatcher, V value)

Shpota avatar Apr 28 '17 08:04 Shpota

+1 on this, especially the first one is useful as you usually know exact key and want to have some vague match for the value.

Also, simplifies the unit test runtime complexity from linear to constant (assuming the map is usually HashMap), And some Maps don't support iterating through entries.

kvr000 avatar Jan 03 '20 21:01 kvr000

@kvr000 this PR has been hanging for 3 years with no response from the maintainers. I have a serious doubt that it will ever be accepted.

Shpota avatar Jan 06 '20 19:01 Shpota

@Shpota does look a good idea, can you rebase from master as hamcrest-core and hamcrest-library has been merged into hamcrest so can't currently merge in currently.

nhojpatrick avatar Jun 28 '20 23:06 nhojpatrick

One caveat is to make sure the overloading works with the extra combinations. Might be worth just doing hasEntry(K key, Matcher<? super V> valueMatcher)

sf105 avatar Jun 29 '20 19:06 sf105

@nhojpatrick the original fork is already gone, that's why I cannot rebase it. Please take a look at this new PR where I applied exactly the same changes on top of the latest version.

@sf105 the overloading does work. There are also tests for that.

I would also prefer keeping both matchers. At least from my use cases, both are applicable, although the hasEntry(Matcher<? super K> keyMatcher, V value) is applicable not that often.

Shpota avatar Jun 30 '20 15:06 Shpota

@nhojpatrick could you please take a look at the updated PR?

Shpota avatar Jul 07 '20 17:07 Shpota

Going to try and kick start hamcrest, so if you want to get it merged, please rebase from the branch v2.3-candidates. Still trying to understand how has permissions to perform a release.

nhojpatrick avatar Feb 13 '22 12:02 nhojpatrick