2013-12-19 86 views
2

我使用Assert.AreEqual比较两个对象。这些对象是同一类的两个不同实例,并且该类中有一个ToString方法。当我调用AreEqual时,我可以从调试器中看到ToString方法被调用(对于这两个变量中的每一个都调用了一次)。AreEqual比较对象与ToString

ToString方法返回确切地说在每种情况下都是相同的字符串,但仍然由于某种原因AreEqual方法返回false。

为什么会这样呢?

的错误是

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> 

回答

3

ToString被简称报告的预期值和实际值。这是而不是什么决定了平等。这就是Equals(object)方法,你应该以提供平等的语义你感兴趣的是压倒一切。(你应该考虑实施IEquatable<T>为好,但这是稍微分开。)

总之,Assert.AreEqual实现东西 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); 
}