Latest Replies
Saturday
Nov292008

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?

« Better Syntax and New Rules for the .NET Validation Block | Main | What is an Action Policy? »

Reader Comments (2)

I like that - great idea! I use extension methods for NUnit that look like:

actual.Should(Be.EqualTo(2.5).Within(0.5));

Not sure if they're well known, but you can find then here.

November 29, 2008 | Unregistered CommenterSean Kearon

Sean,

thanks for the tip. I like the syntax idea. It got me thinking if I could easily add similar one to the Validation and Rules app block.

November 30, 2008 | Registered CommenterRinat Abdullin
Comments for this entry have been disabled. Additional comments may not be added to this entry at this time.