Domanda

I'm using Assert.AreEqual to compare two objects. The objects are two different instances of the same class and there is a ToString method in that class. When I call AreEqual I can see from the debugger that the ToString method gets called (once for each of the two variables).

The ToString method returns exactly the same string in each case but still for some reason the AreEqual method returns false.

Why might this be?

The error is

Additional information:   Expected: <DeliveryTag: 0, RoutingKey: , Body: test, Headers: test: test, ContentType: text/plain>

  But was:  <DeliveryTag: 0, RoutingKey: , Body: test, Headers: test: test, ContentType: text/plain>
È stato utile?

Soluzione

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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top