Improving Debugging And Testing Through Assertions
Reading through the The Typemock Insider blog, I came across this post from Gil Zilberfeld.
I myself tend to fall in Gil’s practice ("binary search" debugging), but I don’t think Kent Beck has the right solution.
Gil’s suggestion of using Isolator is tempting (I don’t miss an opportunity to use it), but still not my favorite one.
I prefer to use debug assertions. Debug assertions can be used when running a debug version of the application to pop-up assertion messages and when running unit tests to fail tests.
In order to use debug assertions in unit tests a “special” trace listener is needed to make the test fail when its Fail method is called.
public class UnitTestTraceListener : global::System.Diagnostics.DefaultTraceListener { public UnitTestTraceListener() : base() { this.Name = "UnitTest"; this.AssertUiEnabled = false; }<span style="color: blue">public override void </span>Fail(<span style="color: blue">string </span>message, <span style="color: blue">string </span>detailMessage) { Microsoft.VisualStudio.TestTools.UnitTesting.<span style="color: #2b91af">Assert</span>.Fail(<span style="color: #a31515">"Debug.Assert Failed: " </span>+ message + <span style="color: #a31515">" " </span>+ detailMessage); }
}
Now, all you need to do is register it.
Registering the trace listener can either be done in code:
System.Diagnostics.Trace.Listeners.Remove("Default"); System.Diagnostics.Trace.Listeners.Add(new UnitTestTraceListener());
or configuration:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.diagnostics> <assert assertuienabled="false"/> <trace> <listeners> <clear/> <add name="UnitTest" type="UnitTestTraceListener"/> </listeners> </trace> </system.diagnostics> </configuration>
And if I’m using Isolator I have the take in account the accesses made in the call to the Assert method. More fun to me.