![](/img/trans.png)
[英]Assert.Equals of Two objects implementing IEquatable(T) doesn't use the equals method
[英]NUnit's Assert.Equals throws exception "Assert.Equals should not be used for assertions"
我最近嘗試在編寫新的 NUnit 測試時使用 Assert.Equals() 方法。 執行時,此方法會拋出一個AssertionException
,說明Assert.Equals should not be used for Assertions.
乍一看,這有點莫名其妙。 這里發生了什么?
Assert
是一個繼承自 System.Object 的靜態類,因為所有類在 C# 中都是隱式執行的。 System.Object 實現以下方法:
static bool Equals(object a, object b)
Assert 上用於相等比較的方法是Assert.AreEqual()
方法。 因此,在單元測試中通過Assert類調用Object.Equals()
方法肯定是錯誤的。 為了避免這種錯誤和混淆,NUnit 的開發人員有意將Object.Equals
隱藏在 Assert 類中,其實現會拋出異常。 這是實現:
/// <summary>
/// The Equals method throws an AssertionException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
// TODO: This should probably be InvalidOperationException
throw new AssertionException("Assert.Equals should not be used for Assertions");
}
當然,異常消息本身令人困惑,但至少它讓您知道您做錯了什么。
tldr;
Assert.AreEqual(a, b); // <-- Compares a, b
不是:
Assert.Equals(a, b); // <-- Irrelevant equality operator on Assert itself
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.