tags:

views:

205

answers:

4

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?

+11  A: 

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
Jason
Can you elaborate on this?
Blake Blackwell
@Blakewell: Sure, see my edit.
Jason
Thank you Jason. This makes perfect sense.
Blake Blackwell
@Blakewell: My pleasure.
Jason
Watch out for Equality Pollution. Overriding Equals may not be the correct thing to do. See here for more information: http://stackoverflow.com/questions/2046121/how-to-compare-two-object-in-unit-test-how-to-compare-two-collection-in-unit-tes/2047576#2047576
Mark Seemann
+3  A: 

The second assert statement actually compares the references of the objects, not the content. Since the parameters of the AreEqual method are of type objects, there's not much information on how the unit test framework should compare these.

EDIT: check this question: http://stackoverflow.com/questions/318210/compare-equality-between-two-objects-in-nunit

Gerrie Schenck
ah..too late :) Was just writing the same :) (+1)
Juri
Ahhhh, good call. Didn't see the nUnit question when I posted.
Blake Blackwell
A: 

For the above to work you need to override Equals and compare all properties there.

Håvard S
+1  A: 
Freddy