I have build some complex objects and I am trying to verify it works correctly by doing some unit testing. This involves comparing some List(Of T), so I tried to use CollectionAssert. Now I encountered something weird.
First I used CollectionAssert.AreEqual to see if the first list was equal. This assertion passed. But for simplicity I wanted to use CollectionAssert.AreEqual, so that I do not have to create the expected object in the exact right order, so I started trying that. With exactly the same code, the CollectionAssert.AreEquivalent failed. I would say this is weird, because equivalent is a looser assertion than equal, right? I get this error:
CollectionAssert.AreEquivalent failed. The expected collection contains 1 occurrence(s) of <MyObject>. The actual collection contains 0 occurrence(s).
I tried debugging, but I didnt get it working to debug the .Net framework, even though I set up downloading the symbol files. So I could only see it enters my custom Equals function once - which returns true - and then the assertion fails. Both objects have two elements. The call stack is (in reversed order):
- CollectionAssert.AreEquivalent
- CollectionAssert.AreEquivalent(overload)
- CollectionAssert.FindMisMatchedElement
- Generic.Dictionary(Of Object, int).TryGetValue
- Generic.Dictionary(Of Object, int).FindEntry
- Generic.ObjectEqualityComparer.Equals
- My custom Equals
Now that I am writing this, an idea came up and I see a potential problem. I see it internally uses a Dictionary. Which probably functions as some sort of hashmap, where the int is the index in the actual list? Does this mean I need to implement a custom IEqualityComparer, rather than overriding equals? And how should my getHashCode() look like then? (I'm guessing that this is crucial then, since I reckon it might be used for the key in the dictionary?)