In hamcrest-java there are matchers IsEmptyCollection, IsCollectionWithSize.
I would like a similar pair to be implemented for java.util.Map, i.e. IsEmptyMap, IsMapWithSize.
A goal is to be able to test that a map is null or empty, like the following: anyOf(nullValue(),emptyMap())
Comment #1
Posted on Feb 1, 2011 by Quick HippoThe Map contract defines that maps (of any concrete type) can be compared for equality. So, isEmptyMap() is the same as equalTo(emptyMap()), where emptyMap is imported from java.util.Collections
IsMapWithSize is a reasonable matcher.
Comment #2
Posted on Feb 10, 2011 by Massive RhinoIf I understand, you're saying that IsEmptyMap shouldn't be a class, because there is a significant difference between the Map contract and the Collection contract. While the "empty map" method can be implemented trivially, the "empty collections" contract can't be trivially implemented because Collections encompass things like Lists, Sets, and Queues, which can't be compared to a "generic empty instance" in the same way maps can.
Despite this, it would still be a nice to have an "emptyMap()" utility method on org.hamcrest.Matchers. This utility method may just be a "one line method" but it's a pretty ugly method:
public static Matcher> emptyMap() { return describedAs("an empty map", equalTo(Collections. emptyMap())); }
There's my best attempt; I've probably screwed it up myself, here, as I tend to take a trial-and-error approach with generics.
Comment #3
Posted on Feb 10, 2011 by Massive RhinoAs an afterthought; it seems like IsEmptyCollection and IsEmptyMap can each be implemented trivially as derivations of IsCollectionWithSize and IsMapWithSize. I'm not sure if this approach is realistic, but it seems like it could cut down on "class clutter" and solve this problem in a somewhat elegant/symmetrical way.
Comment #4
Posted on Jun 14, 2011 by Helpful RabbitThe idea of comparing the map (as mapping) using equality is good, but I think that the issue is more related with the consistency and ease of use of the Hamcrest API, which would benefit from adding this simple method. Thanks for the alternative solution.
Comment #5
Posted on May 12, 2012 by Massive Hippotagging
Comment #6
Posted on Jul 29, 2012 by Massive HippoI have added some new map size matchers in the following commit: https://github.com/hamcrest/JavaHamcrest/commit/749ef4be528e489139aec9d5ad40188078dab389
This should give you access to: is(aMapWithSize(3)) is(aMapWithSize(equalTo(3))) is(anEmptyMap())
Comment #7
Posted on Dec 28, 2012 by Happy ElephantBackport to the hamcrest-java-gwt branch
- issue131-backport.patch 9.78KB
Status: Fixed
Labels:
Java