Checking Exceptions in MsTest

So, we found out MsTest does not have an Assert method to check if your method throws an exception. But can take care of that.

///<summary>
/// Extension methods for MsTest Assert
///
</summary> 
public static class AssertEx
{
///<summary>
/// Check that the peice of code throws an exception
/// as expected
///</summary>
///<typeparam name=”T”></typeparam>
///<param name=”action”></param>
///<returns></returns>
public static T Throws<T>(Action action) where T : Exception
{
try
{
action();
}
catch (T ex)
{
return ex;
}
catch (Exception ex)
{
Assert.Fail(“Expected exception of type {0} but actual exception of type {1} was thrown.”, typeof(T), ex.GetType());
}

Assert.Fail(“Expected exception of type {0} but not exception was thrown.”, typeof(T));
return null;
}
}

This method can be used to run methods which are expected to throw exceptions.

AssertEx.Throws<MyException>( () => class.RunMethodRun() );

This will make sure that the method RunMethodRun() throws an exception or your unit test will fail.

Advertisements

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