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

前端 未结 6 1219
旧时难觅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

    Dictionary class does not override Object.Equals method as seen from MSDN doco:

    http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

    Determines whether the specified Object is equal to the current Object.

    Seeing that you are doing unit testing, your Assert class should provide a test method for testing if two collections are the same.

    Microsoft Unit testing framework provides CollectionAssert class for the purpose of comparing collections:

    http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert_members%28VS.80%29.aspx

    EDIT Dictionary implements ICollection interface, can you see if that just works? You might need to use this overload to compare two dictionary entries.

    EDIT Hmm IDictionary does not implement ICollection, which is a bit of a pain. This however works (albeit a hack):

    IDictionary dict = new Dictionary();
    IDictionary dictClone = new Dictionary();
    
    for(int x = 0; x < 3; x++) {
        dict[x.ToString()] = x;
        dictClone[x.ToString()] = x;
    }
    
    CollectionAssert.AreEqual((System.Collections.ICollection)dict, (System.Collections.ICollection)dictClone);
    

    THe above approach will work for instances of Dictionary, however if you are testing a method that returns IDictionary it might fail if the implmentation changes. My advice is to change the code to use Dictionary instead of IDictionary (since IDictionary is not readonly, so you are not hiding all that much by using that instead of concreate Dictionary).

提交回复
热议问题