Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert.AreEquals calls object.Equals irrespective of IEquatable implemenations

Today when writing and running some tests, I found out that even though my class implemented an IEquatable<MyClass> interface, an Assert.AreEqual(instanceOfMyClass, anotherInstance); resulted in false.

It turns out that no matter what, the Assert.AreEquals calls object.Equals(object obj) instead of the correct MyClass.Equals(MyClass obj) function.

Under the assumption that there is a logical reason, what is it?

like image 363
Sellorio Avatar asked Nov 12 '22 22:11

Sellorio


1 Answers

You could try overloading == on the class in question and use the generic "Assert.AreEqual< T>" overload which uses the equals operator.

Personally I would prefer to use Assert.AreEqual(true,InstanceA.Equals(InstanceB)) as this is sure to use your Equals method; of course this assumes you have unit-tested your Equals method and are 100% certain that it works :)

As to why Assert uses object.Equals, I guess we'd have to ask the designer of the class :) But I suppose one reason is that if your Equals method is buggy, your test result is no good.

like image 188
Stephen Byrne Avatar answered Nov 14 '22 23:11

Stephen Byrne