【问题标题】:C# unit testing with collections of collections使用集合的集合进行 C# 单元测试
【发布时间】:2017-08-16 12:50:06
【问题描述】:

搭载this SO question...

这个测试是怎么失败的?

[TestMethod]
public void DummyTest() {
    var expected = new List<List<string>>() {
        new List<string>(){ "123456", "25.6", "15", "a" },
        new List<string>(){ "123457", "3107450.82", "1", "bcdef" },
        new List<string>(){ "123458", "0.01", "900000", "-fgehk" }
    };

    var actual = new List<List<string>>() {
        new List<string>(){ "123456", "25.6", "15", "a" },
        new List<string>(){ "123457", "3107450.82", "1", "bcdef" },
        new List<string>(){ "123458", "0.01", "900000", "-fgehk" }
    };

    CollectionAssert.AreEqual(expected, actual);
}

顺便说一句,Assert.IsTrue(expected.SequenceEqual(actual)); 也失败了。

有没有更好的方法来测试集合的集合?

使用 .NET 4.6.1。

【问题讨论】:

  • 补充一点,测试失败的结果信息是:“CollectionAssert.AreEqual failed. (Element at index 0 do not match.)”

标签: c# .net unit-testing


【解决方案1】:

该比较方法将查看每个集合中的第一项,检查使用该类型的默认比较器是否相等,如果不相等,则认为外部集合不相等。然后它会以同样的方式继续检查其他元素。

List&lt;string&gt; 的默认相等比较器将比较两个对象的引用,而不是比较两个列表的基础值,因为List 不会改变 object 的默认行为。

您可以编写自己的IComparer,它知道如何检查两个集合是否实际上相等,并将该比较器提供给CollectionAssert,如果您希望使用项目的值比较内部集合中的项目在集合中。

【讨论】:

    【解决方案2】:

    实现这一点的一种方法是使用以下代码:

    public static bool AreEqual<T>(IList<T> list1, IList<T> list2)
    {
        if (list1?.Count != list2?.Count)
            return false;
    
        // order does not matter. Remove OrderBy, if it matters
        // return list1.OrderBy(_ => _).SequenceEqual(list2.OrderBy(_ => _));
        return list1.SequenceEqual(list2);
    }
    
    public static bool AreEqualListOfLists<T>(IList<List<T>> lists1, IList<List<T>> lists2)
    {
        return lists1.All(innerList1 => lists2.Any(innerList2 => AreEqual(innerList1, innerList2)));
    }
    
    static void Main(string[] args)
    {
        var expected = new List<List<string>>
        {
            new List<string> {"123456", "25.6", "15", "b"},
            new List<string> {"123457", "3107450.82", "1", "bcdef"},
            new List<string> {"123458", "0.01", "900000", "-fgehk"}
        };
    
        var actual = new List<List<string>>
        {
            new List<string> {"123456", "25.6", "15", "b"},
            new List<string> {"123457", "3107450.82", "1", "bcdef"},
            new List<string> {"123458", "0.01", "900000", "-fgehk"}
        };
    
        var areEqual = AreEqualListOfLists(expected, actual);
    }
    

    它比SelectMany 解决方案稍长,但它提供了更大的灵活性(例如,如果在更深层次上顺序无关紧要,它可以轻松调整或提供有意义的差异错误消息)。

    【讨论】:

      猜你喜欢
      • 2022-12-15
      • 2018-09-21
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多