Sunday, January 24, 2010

Unit Testing for Exceptions with Visual Studio 2008

The following are the two different ways I've unit tested for Exceptions with Visual Studio 2008.

Using Try / Catch

There first way of testing for Exceptions is by using the try-catch construct:

[TestMethod]
public void TestCard()
{
 var c = new CreditCard();
 try
 {
  c.CardNo = "123"; //Should throw an exception
  Assert.Fail("InvalidCardNoException wasn't thrown");
 }
 catch (InvalidCardNoException)
 {
  Assert.IsTrue(true, "InvalidCardNoException was properly thrown");
 }
}

As you can see from the above example, if the exception isn't thrown, Assert.Fail is called which fails the test; and if it is thrown, we succeed the test with Assert.IsTrue.

But Visual Studio 2008 offers a better way on how to deal with exceptions, by using the ExpectedException Attribute.

Using the ExpectedExceptionAttribute Class

Here is the same example, but this time using the ExpectedException Attribute:

[TestMethod, ExpectedException(typeof(InvalidCardNoException))]
public void TestCard()
{
 var c = new CreditCard();
 c.CardNo = "123"; //Should throw an exception
}