Technology Toolbox

Your technology Sherpa for the Microsoft platform

Jeremy Jameson - Founder and Principal

Search

Search

Testing for Expected Exceptions with Visual Studio

Note
This post originally appeared on my MSDN blog:

Since I no longer work for Microsoft, I have copied it here in case that blog ever goes away.

Since I seem to be on a roll blogging this morning, I thought I'd see if I could get one more in before my baby girl wakes up to have breakfast with "Da-da."

When transitioning a couple of years ago from using NUnit to Visual Studio 2005, I noticed that the ExpectedExceptionAttribute didn't quite do what I expected (no pun intended) based on my experience with NUnit.

With NUnit, you could specify the expected message text of the exception and NUnit would transparently perform an assertion on the actual message. In Visual Studio 2005, I found the following "pattern" useful for mimicking the familiar behavior of NUnit:

[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void FindByWhidWithInvalidWhid()
{
    const string expectedExceptionMessage = "A valid WHID must be specified.\r\nParameter name: whid";

    string project1Url = Properties.Settings.Default.Project1Url;

    SPSite site = new SPSite(project1Url);

    try
    {
        PrimaryDocumentService.FindByWhid(site, 0);
    }
    catch (ArgumentException ex)
    {
        Assert.AreEqual(expectedExceptionMessage, ex.Message);
        throw;
    }
}

The internal try/catch block validates the expected message, whereas the ExpectedException attribute on the method delegates the remaining work to the Visual Studio test manager (i.e. showing green vs. red for each test).

Comments

  1. # Interesting finding - 03/22/2007 « Another .NET Blog

    March 23, 2007 12:33 AM
    liangwu.wordpress.com

Add Comment

Optional, but recommended (especially if you have a Gravatar). Note that your email address will not appear with your comment.
If URL is specified, it will be included as a link with your name.

To prevent spam from being submitted, please select the following fruit: Apple

Grapes
Pear
Apple
Strawberry
Cherries
Watermelon
 
Please add 5 and 1 and type the answer here: