13

当我有一个然后创建一个与实际值相同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;
}
4

2 回答 2

17

问题标题迫使我陈述以下内容:

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

但是,就您而言,订购没有问题。这里的要点是Is.EqualTo()有额外的字典比较代码,如此所述。

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

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

于 2014-03-12T10:32:54.957 回答
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

  • Is.EqualTo()在 NUnit 内部,如果两个对象都是ICollection,则使用CollectionsEqual(x,y)它来迭代两者以找出差异。我想它等于Enumerable.SequenceEqual(x,y)

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

于 2011-06-29T08:44:40.737 回答