C# 如何在单元测试中比较列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11055632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:19:02  来源:igfitidea点击:

How to compare Lists in Unit Testing

c#visual-studio-2010unit-testingmstest

提问by Ray Cheng

How can this test fail?

这个测试怎么会失败?

[TestMethod]
public void Get_Code()
{
    var expected = new List<int>();
    expected.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });

    var actual = new List<int>();
    actual.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });

    Assert.AreEqual(expected, actual);
    // Assert.AreSame(expected, actual)       fails
    // Assert.IsTrue(expected.Equals(actual)) fails
}

采纳答案by Jon Skeet

To make assertions about collections, you should use CollectionAssert:

要对集合进行断言,您应该使用CollectionAssert

CollectionAssert.AreEqual(expected, actual);

List<T>doesn't override Equals, so if Assert.AreEqualjust calls Equals, it will end up using reference equality.

List<T>不会覆盖Equals,因此如果Assert.AreEqual只是调用Equals,它将最终使用引用相等。

回答by Shyju

I guess this will help

我想这会有所帮助

Assert.IsTrue(expected.SequenceEqual(actual));

回答by gettingThereSlowly

this test compares a date input, checks if its a leap year, if so, outputs 20 leap years from the inputted date, if not, outputs the NEXT 20 leap years, myTest.Testing refers to the myTest instance which in turn calls the values from a List called Testing containing the calculated values required. part of an exercise I had to do.

这个测试比较一个日期输入,检查它是否是闰年,如果是,从输入的日期输出 20 个闰年,如果不是,输出 NEXT 20 个闰年,myTest.Testing 指的是 myTest 实例,它依次调用这些值来自一个名为 Testing 的列表,其中包含所需的计算值。我必须做的练习的一部分。

[TestMethod]
        public void TestMethod1()
        {
            int testVal = 2012;
            TestClass myTest = new TestClass();
            var expected = new List<int>();
            expected.Add(2012);
            expected.Add(2016);
            expected.Add(2020);
            expected.Add(2024);
            expected.Add(2028);
            expected.Add(2032);
            expected.Add(2036);
            expected.Add(2040);
            expected.Add(2044);
            expected.Add(2048);
            expected.Add(2052);
            expected.Add(2056);
            expected.Add(2060);
            expected.Add(2064);
            expected.Add(2068);
            expected.Add(2072);
            expected.Add(2076);
            expected.Add(2080);
            expected.Add(2084);
            expected.Add(2088);
            var actual = myTest.Testing(2012);
            CollectionAssert.AreEqual(expected, actual);
        }

回答by Declan

I tried the other answers in this thread, and they didn't work for me and I was comparing collections of objects that had the same values stored in their properties, but the objects were different.

我尝试了该线程中的其他答案,但它们对我不起作用,我正在比较在其属性中存储相同值但对象不同的对象集合。

Method Call :

方法调用:

CompareIEnumerable(to, emailDeserialized.ToIndividual,
            (x, y) => x.ToName == y.ToName && x.ToEmailAddress == y.ToEmailAddress);

Method for comparisons:

比较方法:

private static void CompareIEnumerable<T>(IEnumerable<T> one, IEnumerable<T> two, Func<T, T, bool> comparisonFunction)
    {
        var oneArray = one as T[] ?? one.ToArray();
        var twoArray = two as T[] ?? two.ToArray();

        if (oneArray.Length != twoArray.Length)
        {
            Assert.Fail("Collections are not same length");
        }

        for (int i = 0; i < oneArray.Length; i++)
        {
            var isEqual = comparisonFunction(oneArray[i], twoArray[i]);
            Assert.IsTrue(isEqual);
        }
    }

回答by topham101

If you want to check that each contains the same collection of values then you should use:

如果要检查每个都包含相同的值集合,则应使用:

CollectionAssert.AreEquivalent(expected, actual);

Edit:

编辑:

"Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object." - https://msdn.microsoft.com/en-us/library/ms243779.aspx

“如果两个集合具有相同数量的相同元素,但以任何顺序排列,则它们是等效的。如果它们的值相等,则元素相等,而不是如果它们引用同一个对象。” - https://msdn.microsoft.com/en-us/library/ms243779.aspx

回答by karthik kasubha

List<AdminUser> adminDetailsExpected = new List<AdminUser>()
{
new AdminUser  {firstName = "test1" , lastName = "test1" , userId = 
"001test1"  },
new AdminUser {firstName = "test2" , lastName = "test2" , userId = 
"002test2"   }
};

//Act

//行为

List<AdminUser> adminDetailsActual = RetrieveAdmin(); // your retrieve logic goes here

//Assert

//断言

Assert.AreEqual(adminDetailsExpected.Count, adminDetailsActual.Count);  //Test succeeds if the count matches else fails. This count can be used as a work around to test

回答by Ram Pratap

Fluent assertions does deep comparisons of arrays actualArray.Should().BeEquivalentTo(expectedArray)

Fluent 断言对数组进行深度比较 actualArray.Should().BeEquivalentTo(expectedArray)