ToString
is simply called to report the expected and actual values. It's not what determines equality. That's the Equals(object)
method, which you should be overriding in order to provide the equality semantics you're interested in. (You should consider implementing IEquatable<T>
as well, but that's slightly separate.)
In short, Assert.AreEqual
is implemented something like:
// Somewhat simplified, but right general idea
if (!expected.Equals(actual))
{
// Note how once we've got here, it's too late... the results
// of ToString are irrelevant to whether or not we throw an exception
string expectedText = expected.ToString();
string actualText = actual.ToString();
string message = string.Format("Expected: {0} But was: {1}",
expectedText, actualText);
throw new AssertionFailureException(message);
}