I have two objects in my unit test, the actual and expected object. All properties on the object method are the exact same and if I run the following test:
Assert.AreEqual( expectedObject.Property1, actualObject.Property1);
the result passes as expected. However, when I try to run the following test it fails:
Assert.AreEqual (expectedObject, actualObject);
What am I missing? Can two objects not be compared and do I have to do a check on each property?
You need to override
Equalsfor your object.AssertusesObject.Equals. By default,Object.Equalson objects of reference type performs a reference comparison. That is, two instances of a reference type are equal if and only if they refer to the same object. You want to override this so that instead of a reference comparison being performed a value comparison is performed. Here is a very nice MSDN article on the subject. Note that you also need to overrideGetHashCode. See MSDN fo the guidelines. Here is a simple example:Before:
After: