Tim Huffam

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

  Home  |   Contact  |   Syndication    |   Login
  139 Posts | 0 Stories | 1347 Comments | 659 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).
posted on Friday, June 06, 2008 4:19 PM