汉克雷斯特平等收藏
Hamcrest 是否有匹配器来比较集合是否相等? 有 contains
和 containsInAnyOrder
但我需要 equals
不绑定到具体的集合类型。 例如,我无法将 Arrays.asList 和 Map.values 与 Hamcrest equals
进行比较。
提前致谢!
Is there a matcher in Hamcrest to compare collections for equality?
There is contains
and containsInAnyOrder
but I need equals
not bound to concrete collection type.
E.g. I cannot compare Arrays.asList and Map.values with Hamcrest equals
.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为 hamcrest 的类型签名过于热心。您可以执行此相等比较,但需要在编译之前将
List
对象强制转换为Collection
。我经常不得不使用 Hamcrest 进行转换,这感觉不对,但有时这是让它编译的唯一方法。
This is because of hamcrest's over-zealous type signatures. You can do this equality comparison, but you need to cast the
List
object toCollection
before it'll compile.I often have to do casting with Hamcrest, which feels wrong, but it's the only way to get it to compile sometimes.
转换为集合可能有效,但它对底层集合实现做出了一些假设(例如,顺序?)。更通用的方法是编写自己的匹配器。
这是一个几乎完整的匹配器实现,可以完成您想要的操作(您需要填写导入和描述方法)。请注意,此实现要求两个集合的所有元素都相等,但顺序不一定相同。
Casting to a Collection may work, but it makes some assumptions about the underlying Collection implementations (e.g., order?). A more general approach would be to write your own matcher.
Here's a nearly complete matcher implementation that does what you want (you'll need to fill in the imports and describeTo method). Note that this implementation requires all elements of two collections to be equal, but not necessarily in the same order.
如果您在使用集合实现的 equals 方法时遇到问题,您也可以首先复制集合:
此外,以下方法也可能有效:
If you have trouble with the equals method of the collections implementation, you might also first copy the collections:
Also the following might work: