NUnit 中的 EqualTo() 和 EquivalentTo() 有什么区别?
当我有一个 Dictionary
,然后创建一个全新的Dictionary
与实际值相同。
-
调用
Assert.That(actual, Is.EqualTo(expected));
使测试通过。 -
当使用
Assert.That(actual, Is.EquivalentTo(expected));
时,测试未通过。
EqualTo()
和 EquivalentTo()
之间有什么区别?
编辑:
测试未通过时的异常消息如下:
Zoozle.Tests.Unit.PredictionTests.ReturnsDriversSelectedMoreThanOnceAndTheirPositions:
Expected: equivalent to < [Michael Schumacher, System.Collections.Generic.List`1[System.Int32]] >
But was: < [Michael Schumacher, System.Collections.Generic.List`1[System.Int32]] >
我的代码如下所示:
[Test]
public void ReturnsDriversSelectedMoreThanOnceAndTheirPositions()
{
//arrange
Prediction prediction = new Prediction();
Dictionary<string, List<int>> expected = new Dictionary<string, List<int>>()
{
{ "Michael Schumacher", new List<int> { 1, 2 } }
};
//act
var actual = prediction.CheckForDriversSelectedMoreThanOnce();
//assert
//Assert.That(actual, Is.EqualTo(expected));
Assert.That(actual, Is.EquivalentTo(expected));
}
public Dictionary<string, List<int>> CheckForDriversSelectedMoreThanOnce()
{
Dictionary<string, List<int>> expected = new Dictionary<string, List<int>>();
expected.Add("Michael Schumacher", new List<int> { 1, 2 });
return expected;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题标题迫使我声明以下内容:
对于枚举,
Is.EquivalentTo()
进行比较,允许元素的任何顺序。相反,Is.EqualTo() 会考虑元素的确切顺序,就像 Enumerable.SequenceEqual() 一样。
但是,就您而言,订购没有问题。这里的要点是
Is.EqualTo()
有用于字典比较的额外代码,如 此处。并非如此
Is.EquivalentTo()
。在您的示例中,它将使用object.Equals()
比较KeyValuePair>
类型的值是否相等。由于字典值是引用类型List
,因此使用引用相等来比较它们。如果您修改示例,使列表 {1, 2} 仅实例化一次并在两个词典中使用,则
Is.EquivalentTo()
将成功。The question title forces me to state the following:
For enumerations,
Is.EquivalentTo()
does the comparison allowing any order of the elements.In contrast,
Is.EqualTo()
takes into account the exact order of the elements, likeEnumerable.SequenceEqual()
does.However, in your case, there is no issue with ordering. The main point here is that
Is.EqualTo()
has extra code for dictionary comparison, as stated here.Not so
Is.EquivalentTo()
. In your example, it will compare values of typeKeyValuePair<string,List<int>>
for equality, usingobject.Equals()
. Since the dictionary values are of reference typeList<int>
, reference equality is used for comparing them.If you modify your example such that the List {1, 2} is only instantiated once and used in both dictionaries,
Is.EquivalentTo()
will succeed.两者都适合我:
Is.EqualTo()
,如果两个对象都是ICollection
,则使用CollectionsEqual(x,y)
它迭代两者以找出差异。我猜它等于Is.EquivalentTo
会立即执行此操作,因为仅支持序列:EquivalentTo(IEnumerable)
code>Both works for me:
Is.EqualTo()
inside NUnit, if both objects areICollection
, usesCollectionsEqual(x,y)
which iterates both to find the difference. I guess it's equal toEnumerable.SequenceEqual(x,y)
Is.EquivalentTo
does this immediate because support sequences only:EquivalentTo(IEnumerable)