Object Comparison in Unit Testing

.net, mstest

Solution

You need to override `Equals` for your object. `Assert` uses `Object.Equals`. By default, `Object.Equals` on 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 override `GetHashCode`. See MSDN fo the guidelines. Here is a simple example:

Before:

class Test {
    public int Value { get; set; }
}

Test first = new Test { Value = 17 };
Test second = new Test { Value = 17 };
Console.WriteLine(first.Equals(second)); // false

After:

class Test {
    public int Value { get; set; }
    public override bool Equals(object obj) {
        Test other = obj as Test;
        if(other == null) {
            return false; 
        }
        return this.Value == other.Value;
    }
    public override int GetHashCode() { 
        return this.Value.GetHashCode();
    }
}

Test first = new Test { Value = 17 };
Test second = new Test { Value = 17 };
Console.WriteLine(first.Equals(second)); // true

Problem

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?

Original source

Related problems