为什么 HashSet 比较测试失败,元素的顺序似乎很重要
Why is test failing on HashSet comparison, where the ordering of elements seems to matter
我有显示以下 xUnit.net 输出的测试:
[xUnit.net 00:00:07.1166826] Expected: HashSet<License> [Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9], Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81]]
[xUnit.net 00:00:07.1172482] Actual: HashSet<License> [Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81], Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9]]
我不明白为什么这个测试失败了,貌似是HashSet乱序了。
具体来说,实际 与**预期完全相同。
实际:
HashSet<L> [Stuff [abc], Stuff [123]]
预计:
HashSet<L> [Stuff [123], Stuff [abc]]
HashSet 的文档上写着
A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
我的测试是否 运行 未使用相同的 HashSet 相等性检查的东西?
HashSet
不会覆盖 Equals
,将使用 object.Equals
,这是引用相等。
HashSet
不保证元素的顺序。
如果您使用 Assert.Equal
,那么集合的顺序很重要。
改为使用CollectionAssert.AreEquivalent
。
来源:xUnit : Assert two List<T> are equal?
我有显示以下 xUnit.net 输出的测试:
[xUnit.net 00:00:07.1166826] Expected: HashSet<License> [Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9], Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81]]
[xUnit.net 00:00:07.1172482] Actual: HashSet<License> [Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81], Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9]]
我不明白为什么这个测试失败了,貌似是HashSet乱序了。
具体来说,实际 与**预期完全相同。
实际:
HashSet<L> [Stuff [abc], Stuff [123]]
预计:
HashSet<L> [Stuff [123], Stuff [abc]]
HashSet 的文档上写着
A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
我的测试是否 运行 未使用相同的 HashSet 相等性检查的东西?
HashSet
不会覆盖 Equals
,将使用 object.Equals
,这是引用相等。
HashSet
不保证元素的顺序。
如果您使用 Assert.Equal
,那么集合的顺序很重要。
改为使用CollectionAssert.AreEquivalent
。
来源:xUnit : Assert two List<T> are equal?