26

I want a one liner, in NUnit, that asserts whether two dictionary are the same. i.e., I want a concise version of the below code:

public static void DictionaryAssert<T, U>(Dictionary<T, U> dictionaryResult, Dictionary<T, U> expectedResult)
{
    Assert.AreEqual(dictionaryResult.Count, expectedResult.Count);
    foreach (var aKey in expectedResult.Keys)
    {
        Assert.AreEqual(expectedResult[aKey], dictionaryResult[aKey]);
    }
}

Surely it isn't so difficult, but I can't find the reference, any idea?

Graviton
  • 81,782
  • 146
  • 424
  • 602

3 Answers3

40

Have a look at CollectionAssert.AreEquivalent. This will assert that the two dictionaries have the same contents, but are not necessarily the same instance.

adrianbanks
  • 81,306
  • 22
  • 176
  • 206
  • 3
    I thought they are just for IEnumerable? Dictionary doesn't seem to work, according to my testing. – Graviton Oct 30 '09 at 11:19
  • Dictionary implements IEnumerable. Which version are you using? It works for me on NUnit v2.4. – adrianbanks Oct 30 '09 at 11:25
  • I think I agree with you; however the last time I use CollectionAssert.AreEquivalent my dict comparison somehow fails. nvm, I would just accept your answer first. – Graviton Oct 30 '09 at 11:37
  • forgot to add; as far as my current testing goes, `CollectionAssert.AreEquivalent` are now working – Graviton Oct 30 '09 at 11:37
  • 4
    [NUnit documentation](http://www.nunit.org/index.php?p=collectionAssert&r=2.4) says otherwise: "The AreEqual overloads succeed if the two collections contain the same objects, in the same order. AreEquivalent tests whether the collections contain the same objects, without regard to order." – allonhadaya May 11 '12 at 21:01
  • 1
    CollectionAssert.AreEquivalent will work only if key and value types are structs. As by dafault is uses reference equality. If those generic parameters are reference types, even if object contains same data (but different reference), assert will fail. – Yura Oct 23 '15 at 11:19
  • @Yura Reference equality *also* fails on struct types - `object.ReferenceEquals(1, 1)` - so that explanation does not hold. – user2864740 Jul 17 '17 at 03:24
3

Try using CollectionAssert.AreEqual or CollecitonAssert.AreEquivalent.

Both will compare the collection's items (rather than the collection's reference), but as discussed before, The difference is the item's order within the collections:

  • AreEqual - The collections must have the same count, and contain the exact same items in the same order.
  • AreEquivalent - The collections must contain the same items but the match may be in any order.
Michal Kandel
  • 303
  • 2
  • 10
0

You can write framework agnostic asserts using a library called Should. It also has a very nice fluent syntax which can be used if you like fluent interfaces. I had a blog post related to the same.

http://nileshgule.blogspot.com/2010/11/use-should-assertion-library-to-write.html

Nilesh Gule
  • 1,511
  • 12
  • 13