2013-12-19 178 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); 
}