Comparing Reference Types in Unit Tests.
Posted by Vadim on July 3, 2008
If you’ve done some unit testing, you’re familiar with Assert.AreEqual method. Have you try to compare two objects that have the same value(s) but the AreEqual method tells you that they are not equal? For example let assume that we have a class Point:
And we test for the constructor:
When I run this test using MbUnit, the assertion fails. The reason it fails because Point is a reference type. Actually what is getting compared is objects references (not objects values) and of course they have different references.
One way we could fix it is to make Point a Value Type by replacing class with struct.
This definitely resolves the issue.
Another thing we could do is implement IEquatable<T> interface:
[Updated] However, MbUnit test still will fail because deep inside MbUnit’s AreEqual calls object.Equal(object). In order for AreEqual to succeed in this case, it needs to call generic version of AreEqual. Something like this:
It means we need to modify our test little bit. Instead of AreEquals method we can use IsTrue one.
In software development the same problem can be solved many different ways. I assume that most common solution is going to be comparing some public properties in the object instead of the whole object.
Let assume assume that our Point class has public properties X and Y. Here’s an example how my test would look: