C# 使用 Assert.AreEqual() 比较两个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15547383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:08:02  来源:igfitidea点击:

Comparing Two objects using Assert.AreEqual()

c#unit-testingobjectcomparexunit

提问by Vishweshwar Kapse

I 'm writing test cases for the first time in visual studio c# i have a method that returns a list of objects and i want to compare it with another list of objects by using the Assert.AreEqual()method.

我第一次在 Visual Studio C# 中编写测试用例我有一个返回对象列表的方法,我想使用该Assert.AreEqual()方法将它与另一个对象列表进行比较。

I tried doing this but the assertion fails even if the two objects are identical.

我尝试这样做,但即使两个对象相同,断言也会失败。

I wanted to know if this method, the two parameters are comparing references or the content of the object,

我想知道这个方法,两个参数是比较引用还是比较对象的内容,

Do I have to overload the ==operator to make this work?

我是否必须使==操作员超载才能完成这项工作?

采纳答案by anouar.bagari

If you are using NUnitthis is what the documentation says

如果您使用的NUnit是文档中所说的

Starting with version 2.2, special provision is also made for comparing single-dimensioned arrays. Two arrays will be treated as equal by Assert.AreEqual if they are the same length and each of the corresponding elements is equal. Note: Multi-dimensioned arrays, nested arrays (arrays of arrays) and other collection types such as ArrayList are not currently supported.

从 2.2 版本开始,还为比较单维数组做出了特殊规定。如果两个数组的长度相同并且每个相应的元素相等,则 Assert.AreEqual 将它们视为相等。注意:当前不支持多维数组、嵌套数组(数组的数组)和其他集合类型,例如 ArrayList。

In general if you are comparing two objects and you want to have value based equality you must override the Equalsmethod.

通常,如果您正在比较两个对象并且希望具有基于值的相等性,则必须覆盖该Equals方法。

To achieve what you are looking for try something like this:

要实现您正在寻找的东西,请尝试以下操作:

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; 
    }
}  

and in your unit test:

并在您的单元测试中:

Assert.AreEqual(expectedList.ToArray(), actualList.ToArray());

回答by hoonzis

Assert.AreEqual() compares references. Usually when comparing lists I compare the count of the items and than some properties of one exact item in the list or directly the item in the list (but again it is the reference).

Assert.AreEqual() 比较引用。通常在比较列表时,我比较项目的数量,而不是列表中一个确切项目的某些属性,或者直接比较列表中的项目(但它也是参考)。

If you want to compare objects by content than you would have to implement some recursive Object Comparer, but I don't think it is appropriate for Unit Tests, because you want them to run always as fast as possible.

如果您想按内容比较对象,则必须实现一些递归对象比较器,但我认为它不适合单元测试,因为您希望它们始终尽可能快地运行。

回答by Rune FS

Assert.AreEqual in xUniton .NET will check if the objects are identicalhowever object identity is different from value equallity it would seem you are looking for value equality. Ie. "Are the objects in my list of the same value?" which is why it "fails" the two lists are not identical even though the values of each object in each list might represent the same value.

xUnit.NET 中的Assert.AreEqual将检查对象是否相同,但是对象标识与值相等性不同,看起来您正在寻找值相等性。IE。“我列表中的对象是否具有相同的值?” 这就是为什么它“失败”两个列表并不相同,即使每个列表中每个对象的值可能表示相同的值。

Usually in a testing effort it should be enough to test the count of a collection and key elements.

通常在测试工作中,测试集合和关键元素的数量就足够了。

var count = listA.Count;
Assert.AreEqual(count,listB.Count);
Assert.AreEqual(listA.First(),listB.first());
Assert.AreEqual(listA.Last(),listB.Last());
Assert.AreEqual(listA[count/2],listB[count/2]);

The last test doesn't have to be at the middle element and is simply meant to test an element in the list the only reason why it's not a random element is because you would want to be able to reproduce your test results.

最后一个测试不必在中间元素,只是为了测试列表中的一个元素,它不是随机元素的唯一原因是因为您希望能够重现您的测试结果。

回答by a-1

These answers are far too complicated for the issue. There are no overrides necessary to compare two Lists, and you do not need to break out multiple asserts. Microsoft uses the following class, CollectionAssert.

这些答案对于这个问题来说太复杂了。比较两个列表不需要覆盖,也不需要打破多个断言。Microsoft 使用以下类 CollectionAssert。

CollectionAssert.AreEqual(expectedList, actualList)

This works for Lists, Dictionaries, and whatever else implements ICollection interface.

这适用于列表、字典和任何其他实现 ICollection 接口的东西。

The microsoft documentation is at the following location and details the various types of assertions which can be made on collections

微软文档位于以下位置,详细介绍了可以对集合进行的各种类型的断言

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx

However, as mentioned by @Bart, this does not work as expected on Lists of (complex) Objects, and the Equals method may still need to be overwritten for those cases.

但是,正如@Bart 所提到的,这在(复杂)对象列表上无法按预期工作,并且对于这些情况,可能仍需要覆盖 Equals 方法。

回答by Radu Cosoveanu

You could serialize them and test the resulting string.

您可以序列化它们并测试结果字符串。