.NET Dictionaries have same keys and values, but aren't “equal”

前端 未结 6 1306
旧时难觅i
旧时难觅i 2021-01-17 08:48

This test fails:

using Microsoft.VisualStudio.TestTools.UnitTesting;        

[TestMethod()]
        public void dictEqualTest() {
            IDictionary<         


        
6条回答
  •  忘掉有多难
    2021-01-17 09:19

    If you are specifically interested in how you can fix this from unit testing perspective:

    Try this

    CollectionAssert.AreEquivalent(dict.ToList(), dictClone.ToList());
    

    Explanation

    There are extension methods on IDictionary - such as .ToList() - available in .Net 3.5 and up, which will convert the dictionary into a collection of KeyValuePair that can be easily compared with CollectionAssert.AreEquivalent.

    They'll even give reasonably helpful error messages! Example usage:

    IDictionary d1 = new Dictionary {
        { "a", "1"}, {"b", "2"}, {"c", "3"}};
    
    IDictionary d2 = new Dictionary {
        {"b", "2"}, { "a", "1"}, {"c", "3"}}; // same key-values, different order
    
    IDictionary d3 = new Dictionary {
        { "a", "1"}, {"d", "2"}, {"c", "3"}}; // key of the second element differs from d1
    
    IDictionary d4 = new Dictionary {
        { "a", "1"}, {"b", "4"}, {"c", "3"}}; // value of the second element differs from d1
    
    CollectionAssert.AreEquivalent(d1.ToList(), d2.ToList());
    //CollectionAssert.AreEquivalent(d1.ToList(), d3.ToList()); // fails!
    //CollectionAssert.AreEquivalent(d1.ToList(), d4.ToList()); // fails!
    
    // if uncommented, the 2 tests above fail with error:
    //   CollectionAssert.AreEquivalent failed. The expected collection contains 1
    //   occurrence(s) of <[b, 2]>. The actual collection contains 0 occurrence(s).     
    

提交回复
热议问题