使用 Assert.AreEqual() 比较两个对象 [英] Comparing Two objects using Assert.AreEqual()

查看:20
本文介绍了使用 Assert.AreEqual() 比较两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

推荐答案

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

If you are using NUnit this is what the documentation says

从 2.2 版开始,还特别规定了比较一维数组.两个数组将被视为如果它们的长度相同并且每个对应元素相等.注意:多维数组,嵌套数组(数组的数组)和其他集合类型,例如目前不支持 ArrayList.

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.

一般来说,如果您要比较两个对象并且想要基于值的相等,则必须重写 Equals 方法.

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

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

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

在你的单元测试中:

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

这篇关于使用 Assert.AreEqual() 比较两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆