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.

  1. [TestMethod]
  2. public void TestCard()
  3. {
  4. var c = new CreditCard();
  5. try
  6. {
  7. c.CardNo = “123”//Should throw an exception
  8. Assert.Fail(“InvalidCardNoException wasn’t thrown”);
  9. }
  10. catch (InvalidCardNoException)
  11. {
  12. Assert.IsTrue(true“InvalidCardNoException was properly thrown”);
  13. }
  14. }

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:

  1. [TestMethod, ExpectedException(typeof(InvalidCardNoException))]
  2. public void TestCard()
  3. {
  4. var c = new CreditCard();
  5. c.CardNo = “123”//Should throw an exception
  6. }
Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: