Comparing Two objects using Assert.AreEqual()

后端 未结 5 1050
眼角桃花
眼角桃花 2020-12-30 20:24

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

5条回答
  •  鱼传尺愫
    2020-12-30 20:45

    If you are using NUnit this is what the documentation says

    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.

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

    and in your unit test:

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

提交回复
热议问题