dula
dula

Reputation: 61

Compairing two sorted lists using MS Unit Testing by using CollectionAssert.AreEqual but assert fail though tow lists are equal

I have method which sorts persons by last name as bellow,

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

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

            return list;
        }

I wrote test case as bellow,

[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);
        }

My test case is failing though two sorted lists are equal, anybody have idea ?

Upvotes: 0

Views: 94

Answers (2)

archnae
archnae

Reputation: 391

Look at CompareNETObjects library from Kellerman Software. It saves you from having to write a lot of custom comparers.

Upvotes: 0

Mike Mat
Mike Mat

Reputation: 692

You should know that CollectionAssert.AreEqual for reference types will assert that the items in the collections are the same instances (unless you override Equals method). You can change this behavior by passing a Comparer instance to the assertion method.

For example;

    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;
        }
    }

then you use it like

        CollectionAssert.AreEqual(personListExpected, resultList, new PersonComparer());

Upvotes: 3

Related Questions