Graviton
Graviton

Reputation: 83306

NUnit: The API to Check Whether Two Dictionaries Are the Same

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?

Upvotes: 1

Views: 975

Answers (2)

Matt Hamilton
Matt Hamilton

Reputation: 204259

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?

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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

Upvotes: 0

Related Questions