简体   繁体   English

Assert.AreEquals调用object.Equals而不管IEquatable实现如何

[英]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); 今天在编写和运行一些测试时,我发现即使我的类实现了一个IEquatable<MyClass>接口,一个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. 事实证明,无论如何, Assert.AreEquals调用object.Equals(object obj)而不是正确的MyClass.Equals(MyClass obj)函数。

Under the assumption that there is a logical reason, what is it? 在假设存在逻辑原因的情况下,它是什么?

You could try overloading == on the class in question and use the generic "Assert.AreEqual< T>" overload which uses the equals operator. 你可以尝试在有问题的类上重载==并使用通用的“Assert.AreEqual <T>”重载,该重载使用equals运算符。

Personally I would prefer to use Assert.AreEqual(true,InstanceA.Equals(InstanceB)) as this is sure to use your Equals method; 我个人更喜欢使用Assert.AreEqual(true,InstanceA.Equals(InstanceB))因为这肯定会使用你的Equals方法; of course this assumes you have unit-tested your Equals method and are 100% certain that it works :) 当然这假设你已经对你的Equals方法进行了单元测试,并且100%确定它有效:)

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. 至于Assert使用object.Equals的原因,我想我们不得不问这个类的设计者:)但我想有一个原因是如果你的Equals方法有问题,你的测试结果就不好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM