← Back to team overview

nunit-core team mailing list archive

[Bug 608875] Re: NUnit Equality Comparer incorrectly defines equality for Dictionary objects

 

** Branch linked: lp:nunit-3.0

-- 
NUnit Equality Comparer incorrectly defines equality for Dictionary objects
https://bugs.launchpad.net/bugs/608875
You received this bug notification because you are a member of NUnit
Developers, which is subscribed to NUnit V2.

Status in NUnit Test Framework: Fix Committed
Status in NUnit V2 Test Framework: Fix Released

Bug description:
Using Version 2.5.4

This assertion passes
 
            Assert.That(new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } } == new Dictionary<int, int> { { 0, 0 }, { 2, 2 }, { 1, 1 } });
 

While this one does not
 
            Assert.AreEqual(new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Dictionary<int, int> { { 0, 0 }, { 2, 2 }, { 1, 1 } });

Order is not preserved in a dictionary, and the standard object.equals for dictionary objects will ignore the order in which items were added to the Dictionary.

The offending code in NUnit is in the NUnitEqualityComparer class, line 129
 
           if (x is ICollection && y is ICollection)
                return CollectionsEqual((ICollection)x, (ICollection)y);

Since Dictionary implements ICollection, two dictionary objects being compared will be sent through the CollectionsEqual method, which enforces that the elements in the ICollection must match by index. 

            IEnumerator expectedEnum = x.GetEnumerator();
            IEnumerator actualEnum = y.GetEnumerator();

            int count;
            for (count = 0; expectedEnum.MoveNext() && actualEnum.MoveNext(); count++)
            {
                if (!ObjectsEqual(expectedEnum.Current, actualEnum.Current))
                    break;
            }

To fix it, you'll need to check whether the objects being compared implement IDictionary before checking to see if they implement ICollection, and handle them accordingly. I believe you can probably just use object.equals without providing a specialized equality comparison for Dictionaries.





References