0

I am trying to compare two class Objects in my unit tests but getting exception even though the fields are identical.

[TestMethod]
public async Task getResult()
{
var expectedResult = new List<myClass>(){
    new myClass(){
        Id = 1
        Name = "updatedName"
    }
}
// here I am calling POST method to update the name
// won't include the full code because of brevity

// now getting the result
var actualResult = await this.getResult(1) // getting the result of the above Id

Assert.Equal(expectedResult, actualResult)
}

Exception I get:

myClass
{
    Id = 1
    Name = "updatedName"
} because myClass should match, but found
myClass
{
    Id = 1
    Name = "updatedName"
} 

I am confused as all the fields are identical, so why are they not matching?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Amul123
  • 13
  • 2

1 Answers1

0

Assert.Equal relies on the object's .Equals method (see here). When creating your own classes, you have an option to override this method and add your own logic of comparing two objects equality (e.g., field by field equality checking).

If you do not override it, there is a default .Equals inherited from Object, which is equivalent to .ReferenceEquals: it returns true if the two objects have the same reference and false otherwise. The only situation when the two objects have the same reference is when it's the same object.

In your case, you can either define the .Equals override for your class (e.g., see here) or you can try to follow some of the advice given in this SO answer on how to perform deep equality checking of two objects. Third option is to create a separate class inherited from IEqualityComparer, which will purely provide the equality checking logic for your object while not being a part of your class codebase (for example, see this article).

bazzilic
  • 826
  • 2
  • 8
  • 22