Unit Testing Code with System.Diagnostics.Debug

Matt Ellis has answered Ron Cain’s question about Assert in the context of a test harness. I would answer differently.

When testing code that uses Debug.Assert, you would want to fail the test when that Assert fails. Here is a small piece of code that will do it for you (without needing specialized configuration files, this will keep the test confined in the actual test class and not distributed in several places)

// This Class will fail the test when a Debug.Assert has failed public class TestTraceListener:DefaultTraceListener { public override void Fail(string message, string detailMessage) { Assert.Fail("Debug.Assert Failed: "+message+" "+ detailMessage); } } [Test] public void TestCodeWithFailingDebugAssert() { // use special test tracer Trace.Listeners.Remove("Default"); Trace.Listeners.Add(new TestTraceListener()); // see what happens when a Debug.Assert fails // this is normally hidden somewhere deep inside the code Debug.Assert(false); }

Add Comment

Required fields are marked *. Your email address will not be published.