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?
Object comparison refers to the ability of an object to determine whether it is essentially the same as another object. You evaluate whether one object is equal to another by sending one of the objects an isEqual: message and passing in the other object.
assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .
AreEqual(Object, Object, String) Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
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
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: Compare equality between two objects in NUnit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With