NUnit: Dictionary Assert

亡梦爱人 提交于 2019-12-22 01:25:49

问题


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?


回答1:


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




回答2:


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




回答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.


来源:https://stackoverflow.com/questions/1649161/nunit-dictionary-assert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!