How to compare Lists in Unit Testing

后端 未结 7 1572
闹比i
闹比i 2020-11-30 00:24

How can this test fail?

[TestMethod]
public void Get_Code()
{
    var expected = new List();
    expected.A         


        
7条回答
  •  误落风尘
    2020-11-30 00:58

    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(IEnumerable one, IEnumerable two, Func 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);
            }
        }
    

提交回复
热议问题