Equality Testing in NUnit

2/19/2004 1:01:39 PM

Equality Testing in NUnit

A common problem with unit-testing with NUnit is to accidentally invoke Assert.Equals instead of Assert.AreEquals. Assert.Equals has the the same signature as Assert.AreEquals, but it is actually a static method inherited from Object.Equals. As a consequence, no failure is ever reported. (Steve Eichart has reported encountering the same problem.)

The solution is for the NUnit developers to define a new method in their AssertClass that shadows (to use a VB term) the inherited method using the "new" keyword.

public static new void Equals(object obj1, object obj2)
   Assert.Fails("Use AreEquals instead of Equals.");

Unfortunately, the method has to be nonprivate for shadowing to work. In this case, it is public, so that the compiler does not actually proceed further to the base class.

The other problem is either that the NUnit developers will need to implement this in their next release or that end developers need to change and recompile the NUnit libraries. I sent a mail to two of the developers informing them of this bug and the fix, but I encourage anyone reading this post to go to nunit.org and barrage the NUnit developers with additional email to fix and prevent this bug from actually occurring out of the box.

The current solution that I use is to create a base class for test classes and have every text fixture derived from that base class.

In that class, I have static methods for AreEqual, IsNull, etc, that call into the actual NUnit methods. The benefits of adding these static methods include (1) calling AreEqual directly without prefixing the Assert class name and (2) customized the behavior of each Assert method. For example, my AreEquals method breaks (Debugger.Break) into the debugger when a debugger is attached (Debugger.IsAttached). When the debugger is not attached, the methods simply call into their actual NUnit counterpart.

My base class also contains test cases for testing various kinds of common object operation such as equality, ICompare, cloning, overloaded operators such as ==, !=, <=. In addition, I have a class for testing objects derived from IEnumerable, ICollection and IList.






Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media