我最近尝试在编写新的NUnit测试时使用Assert.Equals()方法.在执行时,这种方法抛出一个AssertionException说明,
Assert.Equals should not be used for Assertions. 乍一看这有点莫名其妙.这里发生了什么?
Odr*_*ade 193
Assert是一个继承自System.Object的静态类,因为所有类都在c#中隐式执行.System.Object实现以下方法:
static bool Equals(object a, object b)
Run Code Online (Sandbox Code Playgroud)
用于等式比较的Assert Assert.AreEqual()方法是方法.因此,Object.Equals()在单元测试中通过Assert类调用该方法肯定是一个错误.为了防止这种错误并避免混淆,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");
}
Run Code Online (Sandbox Code Playgroud)
当然,异常消息本身令人困惑,但至少它会让你知道你做错了什么.
Dou*_*oug 13
tldr;
Assert.AreEqual(a, b); // <-- Compares a, b
Run Code Online (Sandbox Code Playgroud)
不:
Assert.Equals(a, b); // <-- Irrelevant equality operator on Assert itself
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18886 次 |
| 最近记录: |