当我有一个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]] >


我的代码如下所示:

[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;
}

最佳答案

两者都对我有用:

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





如果两个对象都是Is.EqualTo(),则在NUnit中使用ICollection,并使用CollectionsEqual(x,y)对其进行迭代以查找差异。我想这等于Enumerable.SequenceEqual(x,y)
Is.EquivalentTo立即执行此操作,因为仅支持序列:EquivalentTo(IEnumerable)

07-27 21:36