NUnit的的Assert.Equals抛出异常" Assert.Equals不应该被用于断言"断言、抛出、异常、Assert

2023-09-02 20:49:35 作者:过分温柔

我最近尝试使用()写一个新的NUnit测试方法时Assert.Equals。在执行此方法将引发 AssertionException 说明 Assert.Equals不应该被用于断言。这是一个有点莫名其妙乍一看。这是怎么回事吗?

I recently attempted to use the method Assert.Equals() when writing a new NUnit test. Upon execution this method throws an AssertionException stating that Assert.Equals should not be used for Assertions. This is a bit baffling at first glance. What's going on here?

推荐答案

断言是一个静态类从System.Object继承,因为所有的类在C#中做的含蓄。 System.Object的实现以下的方法:

Assert is a static class inheriting from System.Object, as all classes do implicitly in c#. System.Object implements the following method:

static bool Equals(object a, object b)

这是用于相等的比较上断言的方法是Assert.AreEqual()的方法。因此,呼吁通过断言类的Object.Equals()方法在单元测试肯定是一个错误。为了prevent这个错误和避免混淆,NUnit的开发商故意隐藏的Object.Equals 的断言类抛出异常的实现。这里的实现:

The methods on Assert which are intended for equality comparison are the Assert.AreEqual() methods. Therefore, calling the Object.Equals() method through the Assert class in a unit test is certainly a mistake. In order to prevent this mistake and avoid confusion, the developers of NUnit have intentionally hidden Object.Equals in the Assert class with an implementation that throws an exception. Here's the implementation:

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

当然,除了消息本身是混乱的,但至少它可以让你知道你做的的东西的错误。