NUnit中EqualTo()和EquivalentTo()有什么区别?

Gar*_*ghi 10 .net nunit unit-testing nunit-2.5

当我有一个Dictionary<string, int> actual然后Dictionary<string, int> expected用与实际相同的值创建一个全新的.

  • 调用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]] >
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样:

[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;
}
Run Code Online (Sandbox Code Playgroud)

tm1*_*tm1 11

问题标题迫使我说明以下内容:

对于枚举,Is.EquivalentTo()比较是否允许元素的任何顺序.相反,Is.EqualTo()考虑到元素的确切顺序,就像Enumerable.SequenceEqual()这样.

但是,在您的情况下,订购没有问题.这里主要的一点是,Is.EqualTo()有字典比较额外的代码,表示在这里.

不是这样Is.EquivalentTo().在您的示例中,它将KeyValuePair<string,List<int>>使用相等的类型值进行比较object.Equals().由于字典值是引用类型List<int>,因此引用相等用于比较它们.

如果您修改示例以使List {1,2}仅实例化一次并在两个词典中使用,Is.EquivalentTo()则会成功.


aba*_*hev 5

两者都适合我:

var actual = new Dictionary<string, int> { { "1", 1 }, { "2", 2 } };
var expected = new Dictionary<string, int> { { "1", 1 }, { "2", 2 } };

Assert.That(actual, Is.EqualTo(expected)); // passed
Assert.That(actual, Is.EquivalentTo(expected)); // passed
Run Code Online (Sandbox Code Playgroud)
  • Is.EqualTo()在 NUnit 内部,如果两个对象都是ICollection,则使用CollectionsEqual(x,y)it 迭代两者来查找差异。我想它等于Enumerable.SequenceEqual(x,y)

  • Is.EquivalentTo立即执行此操作,因为仅支持序列:EquivalentTo(IEnumerable)