测试两个字典包含相同的元素

Test two Dictionaries contain the same elements

MSTest 提供 CollectionAssert class 并且基于这个问题我正在比较返回的词典是否符合我的期望:.NET Dictionaries have same keys and values, but aren't "equal"

然而,我故意以与返回版本不同的顺序填充我的字典,但使用完全相同的元素...现在 CollectionAssert.AreEqual 在我调用时失败:

CollectionAssert.AreEqual((ICollection)expected, (ICollection)ret)

这似乎不是一个很好的相等性测试 - 我需要自己推出还是 MSTest 提供开箱即用的东西?

您可以使用 AreEquivalent:

CollectionAssert.AreEquivalent((ICollection)expected, (ICollection)ret)

此方法测试集合是否具有相同数量但顺序任意的相同元素。

在同一个 class 中还有另一个方法叫做 AreEquivalent();

如果您作为参数发送的两个 ICollection 对象具有相同数量的相同元素,这将 return 为真。在这种情况下,顺序无关紧要。这是AreEqual()和AreEquivalent()最大的区别。

下面是MSDN页面的官方解释。

"Verifies that the specified collections are equivalent. Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object."

你对该函数的调用与你对 AreEqual() 的调用相同,见下文;

CollectionAssert.AreEquivalent((ICollection)expected, (ICollection)ret)