NUnit的Assert.Equals抛出异常“Assert.Equals不应该用于断言”

时间:2012-07-20 17:46:43

标签: .net nunit

我最近尝试在编写新的NUnit测试时使用Assert.Equals()方法。在执行时,此方法抛出AssertionException表明 Assert.Equals should not be used for Assertions.乍一看这有点令人费解。这是怎么回事?

2 个答案:

答案 0 :(得分:186)

Assert是一个继承自System.Object的静态类,因为所有类都在c#中隐式执行。 System.Object实现以下方法:

static bool Equals(object a, object b)

用于等式比较的Assert方法是Assert.AreEqual()方法。因此,在单元测试中通过Assert类调用Object.Equals()方法肯定是一个错误。为了防止这种错误并避免混淆,NUnit的开发人员故意在Assert类中使用一个抛出异常的实现隐藏Object.Equals。这是实施:

/// <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");
 }

当然,异常消息本身令人困惑,但至少它会让你知道你已经完成了某些错误。

答案 1 :(得分:9)

tldr;

Assert.AreEqual(a, b); // <-- Compares a, b

Assert.Equals(a, b); // <-- Irrelevant equality operator on Assert itself