23 Januar 2010

New NUnit syntax of how to expect exceptions

I have just stumbled upon a new beautiful syntax of how you can write a unit tests that expects that a method throws a certain exeception or an exception derived from it. First your test fixture needs to inherit from AssertionHelper which gives you the static Expect method. Then you can implement a test like this:

public void GetExternals_InvalidWorkingCopy_ThrowsSvnException()
    // Arange
    var ep = new WorkingCopyCache();

    // Act & Assert            
    Expect(() => ep.Get(@"X:\Dummy"), Throws.InstanceOf<SvnException>());

To be honest this constraint based syntax exists for quite a while now, but I just didn’t know before. IMHO it is very powerful and readable, compared to other solutions. For more details about how NUnit evolved to finally arrived at this syntax see this blog http://nunit.com/blogs/?p=63.