An xUnit.net Assert.Throws() Code Snippet

Tuesday, June 24, 2008 – 3:51 PM

Choose the 'throws' snippetI was mucking around with code snippets over the weekend – it killed the time in between feeling sick. As my unit testing framework of choice is XUnit I thought I’ve have a go at adding a snippet or two around that.

xUnit already comes with a nice code snippet for creating a method decorated with the Fact attribute. The only other piece of code I find myself (re)writing a lot is code around testing correct exception behavior.

  public class MyTests
  {
    [Fact]
    public void FactName()
    {
      Assert.Throws<ArgumentNullException>(
      delegate
      {
          //throw ...
      });
    }
  }

With a code snippet this becomes a much quicker process. Just type the snippet keyword “throws” and then TAB (like the picture above).

Replace the default Exception type

Next type the expected exception type and RETURN to put the cursor inside the delegate (see picture left).

Installing

All you have to do is save this snippet file Xunit.AssertThrows (CS).snippet into your C# snippets folder. Right click on the link, select “Save Target As…” and change the file extension to “.snippet”. Save it to the

My Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets\

You should be good to go. Open up your xUnit.net tests and give it a try.

Further details of how to install snippets can be found on the Xunit code snippets page.

Currently listening to:
Jello Biafra with D.O.A. – Last Scream of the Missing Neighbors

 

Sorry, comments for this entry are closed at this time.