使用CollectionAssert.AreEqual使用MS Unit Testing对两个排序列表进行比较,但断言列表相同则断言失败

时间:2017-11-04 23:55:34

标签: c# unit-testing

我的方法是按照姓氏对人进行排序,

public List<Person> SortByLastNameFirst(List<Person> list) {

            list.Sort(delegate(Person pFirst,Person pSecond) 
            {
                return pFirst.lastName.CompareTo(pSecond.lastName);
            });

            return list;
        }

我在下面写了测试用例,

[TestMethod]
        public void SortByLastNameFirst_ValidList()
        {
            //arrange
SorterByLastNameFirst sorterObj = new SorterByLastNameFirst(); //class that SortByLastNameFirst method implemented
            List<Person> personList = new List<Person>();
            personList.Add(new Person() { lastName = "Smith", givenName = "William" });
            personList.Add(new Person() { lastName = "Nelson", givenName = "Ola" });

            List<Person> personListExpected = new List<Person>();
            personListExpected.Add(new Person() { lastName = "Smith", givenName = "William" });
            personListExpected.Add(new Person() { lastName = "Nelson", givenName = "Ola" });

            //act
            var resultList = sorterObj.SortByLastNameFirst(personList);

            personListExpected.Sort(delegate (Person pFirst, Person pSecond)
            {
                return pFirst.lastName.CompareTo(pSecond.lastName);
            });

            //assert
            CollectionAssert.AreEqual(personListExpected, resultList);
        }

我的测试用例失败了,虽然两个排序列表相同,有人有想法吗?

2 个答案:

答案 0 :(得分:3)

您应该知道引用类型的CollectionAssert.AreEqual将声明集合中的项是相同的实例(除非您重写Equals方法)。您可以通过将Comparer实例传递给断言方法来更改此行为。

例如;

    class PersonComparer : Comparer<Person>
    {
        public override int Compare(Person x, Person y)
        {
            // 2 Persons are the same if givenName and lastName are the same.
            if (x.givenName == y.givenName && x.lastName == y.lastName)
            {
                return 0;
            }
            return 1;
        }
    }

然后你就像

一样使用它
        CollectionAssert.AreEqual(personListExpected, resultList, new PersonComparer());

答案 1 :(得分:0)

查看Kellerman Software的CompareNETObjects library。它使您不必编写大量自定义比较器。