Assert.AreEqual在比较两个IEnumerable对象时引发异常

时间:2017-03-21 16:17:57

标签: c# unit-testing nunit

目标方法的Moq输入列表是

var moqReturn = new List<Text>()
{
    new Text() {Id = 0, SenderId = 3, ReceiverId = 5},
    new Text() {Id = 1, SenderId = 5, ReceiverId = 1},
    new Text() {Id = 2, SenderId = 1, ReceiverId = 5},
    new Text() {Id = 3, SenderId = 3, ReceiverId = 5},
    new Text() {Id = 4, SenderId = 3, ReceiverId = 5},
    new Text() {Id = 5, SenderId = 5, ReceiverId = 4},
    new Text() {Id = 6, SenderId = 5, ReceiverId = 4},
    new Text() {Id = 7, SenderId = 5, ReceiverId = 10}
};

测试下的方法是:给定userId = 5,top = 3,start = 0

public IEnumerable<Text> GetRecentTexts(int userId, int top, int start)
{
     var allUserTexts = _textRepo.Select(m => m.SenderId == userId || m.ReceiverId == userId); // Will get the moq return

     var recenteText = allUserTexts.Reverse();

     return recenteText.Skip(start).Take(top);
 }

预期输出

  var expectedOutPut = new List<Text>()
    {
        new Text() {Id = 7, SenderId = 5, ReceiverId = 10},
        new Text() {Id = 6, SenderId = 5, ReceiverId = 4},
        new Text() {Id = 5, SenderId = 5, ReceiverId = 4}
    };

使用NUnit的断言方法

var result = objectForTarget.GetRecentTexts(5, 3, 0);

Assert.AreEqual(expectedOutPut, result);

问题是Assert Method显示消息测试失败

<System.Collections.Generic.List`1[Text]> with 3 elements, actual is <System.Linq.Enumerable+<TakeIterator>d__24`1[Text]>
  Values differ at index [0]
  Expected: <Text>
  But was:  <Text>

我调试了目标方法,它返回了预期的结果,但NUnit Assert表示它们不一样。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

Assert.AreEqual将比较两个不同的列表的引用。

使用CollectionAssert.AreEqual比较馆藏

然后您需要Text override the Equals methods或提供IComparer

答案 1 :(得分:1)

正如一些评论和Ofir的答案所示,你必须覆盖Text的Equals方法。否则,使用object.Equals

您必须使用CollectionAssert.AreEqual这是不正确的。它与Assert.AreEqualAssert.That(..., Is.EqualTo(...))没有任何区别。 CollectionAssert没有任何意义,只是为了让MsTest用户更容易转换为NUnit。

两个集合的类型需要相等也是不正确的。 NUnit根据内容比较数组,集合,列表和枚举的内容。