问题
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