Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

.net - NUnit's Assert.Equals throws exception "Assert.Equals should not be used for assertions"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...