Geeks With Blogs

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

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).
Posted on Friday, June 6, 2008 4:19 PM C# .NET , Unit Testing | Back to top


Comments on this post: Checking ExpectedException and is thrown by specified type

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

Your comment:
 (will show your gravatar)


Copyright © Tim Huffam | Powered by: GeeksWithBlogs.net