NUnit's Assert.Equals throws exception “Assert.Equals should not be used for assertions”

后端 未结 2 1036
情书的邮戳
情书的邮戳 2020-12-13 16:56

I recently attempted to use the method Assert.Equals() when writing a new NUnit test. Upon execution this method throws an AssertionException stating that

相关标签:
2条回答
  • 2020-12-13 17:20

    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)
    

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

    Of course the exception message itself is confusing, but at least it lets you know you've done something wrong.

    0 讨论(0)
  • 2020-12-13 17:29

    tldr;

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

    not:

    Assert.Equals(a, b); // <-- Irrelevant equality operator on Assert itself
    
    0 讨论(0)
提交回复
热议问题