Vis*_*pse 32 c# unit-testing compare xunit object
我正在第一次在visual studio中编写测试用例c#我有一个返回对象列表的方法,我想通过使用该Assert.AreEqual()方法将它与另一个对象列表进行比较.
我尝试这样做,但即使两个对象相同,断言也会失败.
我想知道这个方法,这两个参数是比较引用还是对象的内容,
我是否必须让==操作员超负荷工作?
a-1*_*a-1 43
这些答案对于这个问题来说太复杂了.比较两个列表没有必要的覆盖,您不需要打破多个断言.Microsoft使用以下类CollectionAssert.
CollectionAssert.AreEqual(expectedList, actualList)
Run Code Online (Sandbox Code Playgroud)
这适用于Lists,Dictionaries以及其他任何实现ICollection接口的内容.
microsoft文档位于以下位置,并详细说明了可以对集合进行的各种类型的断言
但是,正如@Bart所提到的,这对于(复杂)对象的列表没有预期的效果,并且对于这些情况,可能仍需要覆盖Equals方法.
ano*_*ari 24
如果你正在使用NUnit这是文档说的
从2.2版开始,还对比较单维数组进行了特殊规定.如果两个数组的长度相同且每个相应的元素相等,则Assert.AreEqual将两个数组视为相等.注意:目前不支持多维数组,嵌套数组(数组数组)和其他集合类型(如ArrayList).
通常,如果要比较两个对象并且希望具有基于值的相等性,则必须覆盖该Equals方法.
要实现您的目标,请尝试以下方法:
class Person
{
public string Firstname {get; set;}
public string Lastname {get; set;}
public override bool Equals(object other)
{
var toCompareWith = other as Person;
if (toCompareWith == null)
return false;
return this.Firstname == toCompareWith.Firstname &&
this.Lastname == toCompareWith.Lastname;
}
}
Run Code Online (Sandbox Code Playgroud)
在你的单元测试中:
Assert.AreEqual(expectedList.ToArray(), actualList.ToArray());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59794 次 |
| 最近记录: |