用于检查对象相等性的 XUnit 断言 [英] XUnit Assertion for checking equality of objects
问题描述
我正在使用 XUnit 框架来测试我的 C# 代码.
I am using XUnit framework to test my C# code.
在这个框架中是否有任何可用的断言方法来进行对象比较?我的目的是检查对象的每个公共和私有成员变量是否相等.
Is there any assert method available in this framework which does the object comparison? My intention is to check for equality of each of the object's public and private member variables.
我尝试了这些替代方法,但很少奏效:
I tried those alternatives but seldom it works:
1) bool IsEqual = (Obj1 == Obj2)
2) Assert.Same(Obj1, Obj2) which I couldnt understand what happens internally
推荐答案
你需要有一个自定义的比较器来实现这一点,当你比较对象时,否则会根据它们是否引用内存中的同一个对象来检查它们.要覆盖此行为,您需要覆盖 Equals
和 GetHashCode
方法,然后您可以执行以下操作:
You need to have a custom comparer to achieve this, when you compare objects otherwise they are checked on the basis of whether they are referring to the same object in memory. To override this behavior you need to override the Equals
and GetHashCode
method and then you could do:
Assert.True(obj1.Equals(obj2));
这是一个 MSDN 页面 abt 重载 Equals 方法:http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
Here is an MSDN page abt overloading Equals method: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
还对问题发表评论:什么是IEquatable 和只是覆盖 Object.Equals() 的区别?
这篇关于用于检查对象相等性的 XUnit 断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!