tags:

views:

97

answers:

2

Given two dictionaries

var dictA = new Dictionary<string, classA>();
var dictB = new Dictionary<string, classA>();

How to check whether these two dictionaries are the same? The catch here is that I can't use the default classA.Equals for comparing the value pairs. Instead, the test will pass when and only when given that all the object of the classA type in the dictionaries must satisfy my own custom IEqualityComparer<ClassA>.

Specifically, I am looking at something like

CollectionAssert.AreEquivalent(dictA, dictB, new ClassEqualityComparer());

with ClassEqualityComparer inherits from IEqualityComparer<ClassA>, or equivalent. I don't mind if I have to subclass a NUnit type of IEqualityComparer ( such as IResolveConstraint), but the most important thing is that the Assert method must be something like

Assertion(dictA, dictB, EqualityComparer)

Or something even more simpler; I don't want to use Assert.That and then implement a type of IResolveConstraint that runs into pages just to check whether two dictionaries are the same.

Any idea?

A: 

If you have control over the instantiation of these dictionaries in your unit tests you may pass a comparer to the appropriate constructor.

Darin Dimitrov
That `comparer` only compares between the key of the dictionary, it doesn't compare between the values.
Ngu Soon Hui
If you want to compare values, a list would be more appropriate data type than a hashtable.
Darin Dimitrov
@Darin, I can't because a list comparison would mean that I have to get the order of item right. In my comparison, the orders are not important.
Ngu Soon Hui
+1  A: 

So I guess you'll need to test that dictionary "B" contains all the same keys as "A" and vice versa, and then use your comparer to compare each value:

Assert.IsTrue(dictA.Keys.All(k => dictB.ContainsKey(k));
Assert.IsTrue(dictB.Keys.All(k => dictA.ContainsKey(k));

var cmp = new ClassEqualityComparer();
Assert.IsTrue(dictA.Keys.All(k => cmp.Equals(dictA[k], dictB[k]));

Will that work?

Matt Hamilton
Matt, that will work; in fact I have my own version of code that does more or less the same thing. But I want something built-in. After all dictionary comparison should be common enough to warrant a place in NUnit, or no?
Ngu Soon Hui