Software Design Blog

Journey of Rinat Abdullin

Shortcuts for NUnit Exception Expectations

Are you tired of specifying NUnit exception expectations?

[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void Reference_Value_Is_Checked_For_Null()
{
  // if you have R#, this should be highlighted
  Result.Success<object>(null);
}

There is a shortcut that is more compact:

[Test]
[Expect.ArgumentNull]
public void Reference_Value_Is_Checked_For_Null()

and also has nice IntelliSense:

You just need to define class like this:

static class Expect
{
  public sealed class ArgumentNull : 
    ExpectedExceptionAttribute
  {
    public ArgumentNull()
      : base(typeof(ArgumentNullException)) {}
  }

  public sealed class InvalidOperation : 
    ExpectedExceptionAttribute
  {
    public InvalidOperation()
      : base(typeof(InvalidOperationException)) {}
  }   

  // you get the idea
}

What do you think?