Login using System.Noticeably.Different.WebSite;
February 05, 2012 NoticeablyDifferent
Search for
 
Testing System.Diagnostics 
    #region Code
public class Foo {
    public Foo(string name) {
        Debug.Assert(!String.IsNullOrEmpty(name), "name cannot be null or empty");
    }
}
    #endregion
 
    #region Unit Tests
public delegate void TraceListenerHandler(object sender, EventArgs args);
 
public class MyTraceListener : TraceListener {
    EventHandler handler;
 
    public MyTraceListener(EventHandler handler) {
        this.handler = handler;
    }
 
    public override void Write(string message) {
        handler(thisnew EventArgs());
    }
 
    public override void WriteLine(string message) {
        handler(thisnew EventArgs());
    }
    }
 
[TestFixture]
public class FooTestFixture {
    Foo foo;
    bool assertSuccessful;
    MyTraceListener listener;
 
    public FooTestFixture() { }
 
    [SetUp]
    public void SetUp() {
        assertSuccessful = true;
        listener = new MyTraceListener(
            delegate(object sender, EventArgs args) { assertSuccessful = false; });
        Debug.Listeners.Add(listener);
    }
 
    [TearDown]
    public void TearDown() {
        Debug.Listeners.Remove(listener);
    }
 
    [Test]
    public void DebugAssertCausesValidationFailure() {
        Assert.IsTrue(assertSuccessful);
        try {
            foo = new Foo(null);
        } catch { }
        Assert.IsFalse(assertSuccessful);
    }
}
    #endregion
 
 
The drawback of the previous approach is two-fold. First, when run in nunit-console, a message pops up that I haven't been able to figure out how to supress. Second, when run through fxcop, it states you still haven't validated the parameter passed in (in this case, the 'name' parameter of the constructor in the Foo class). That leaves you with one option, to change the Assert statement to evaluate and throw an exception and test for the expected exceptions in two separate NUnit tests.
 
    #region Code
public class Foo {
    public Foo(string name) {
        if (name == null) throw new ArgumentNullException("name");
        if (name.Length == 0) throw new ArgumentException("name must be at least 1 character in length");
    }
}
    #endregion