Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionAssert.Contains(myList, myItem) != Assert.IsTrue(myList.Contains(myItem))

I have been looking at implementing unit tests for a controller controller, specifically around testing collections. On the MSDN example the use of CollectionAssert.Contains() confirms whether an object appears in a list.

I have a List<myObject> where myObject implements IEquatable (i.e. implementing a Equals(), so that the List<myObject>.Contains() is able to correctly discern the existence (or non-existence of an object of type myObject in the list).

The CollectionAssert.Contains() (for an MS-VS test, not nunit) function however, does not appear to call Equals(). So I'm wondering if it's for use on simple arrays? If not, how is it able to compare custom objects?

I've simply changed my assert in this case to Assert.IsTrue(myList.Contains(myObjectInstance)).

like image 797
Daniel Avatar asked Dec 17 '22 09:12

Daniel


1 Answers

Looking at the code for CollectionAssert.Contains(), the actual comparison is done by iterating the collection, and comparing each element to the target elements with object.Equals(current, target).

So the answer to your question is that if you haven't overridden the object version of Equals() so that it dispatches to your IEquatable<T> version, you should. Otherwise the test is going to fail if reference equality isn't satisfied, since the IEquatable<T> overload of Equals() doesn't override the overload inherited from object.

like image 124
dlev Avatar answered Dec 28 '22 23:12

dlev