Tim Huffam

Dotting the I and crossing the T of I.T.

  Home  |   Contact  |   Syndication    |   Login
  152 Posts | 0 Stories | 2310 Comments | 653 Trackbacks

News

Archives

Post Categories

Interesting Blogs/Links

Using the VS2008 unit testing framework, if you want to check for an expected exception, sometimes your test will pass because the exception was raised by another line of code - after the line you were specifically trying to test.

To resolve this you have to manually check for the expected exception - using a try-catch block. 

However there is a catch (excuse the pun)....

Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType() will not fail when types are different as long as the actual value is of a type within the inheritance hierarchy of the expected type. 

Eg the following assertion will not fail if ex is of type ArgumentNullException - as it inherts from ArgumentException.

Assert.IsInstanceOfType(ex, typeof(ArgumentException));

One solution is to create your own assertion method eg:

 

public static void ExpectedExceptionThrownByType(Type expectedExceptionType, Exception actualException, Type expectedThrownByType)
{
    Assert.AreEqual(expectedExceptionType, actualException.GetType());
    Assert.AreEqual(actualException.TargetSite.DeclaringType, expectedThrownByType, "Expected exception to be thrown by type " + expectedThrownByType.ToString() + " but was " + actualException.TargetSite.DeclaringType.ToString());
}
Note the first assertion uses AreEqual instead of IsInstanceOf() - this makes sure the exception is of a specific type (rather than any one up the inheritance heirarchy).
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Friday, June 06, 2008 4:19 PM

Feedback

# re: Checking ExpectedException and is thrown by specified type 12/14/2011 6:54 AM Cheapbagshoppingcom
cheapbagshopping.com---wholesale cheap men and women clothing,bags,shoes,jewelries,accessories from China.www.cheapbagshopping.com
cheap Vivienne Earrings on sale from China

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: