ExpectedException – Doh!

Every time I learn an easier way to do something, I'm glad I learned it, but I feel like an idiot for not finding it sooner.  Here's a perfect example.  Here's the hard way to check for an expected exception in a VSTS unit test:


/// <summary>
/// Test for an expected exception - the hard way
/// </summary>
[TestMethod]
public void TestForExceptionWorse()
{
bool caughtErr = false;
try
{
MyClass.MethodThatThrowsException();
}
catch (SpecificExceptionToCatch)
{
caughtErr = true;
}
Assert.IsTrue(caughtErr, "Expected SpecificExceptionToCatch, but none was thrown.");
}

It turns out there's an easier way to do this:


/// <summary>
/// Test for an expected exception - the easy way
/// </summary>
[TestMethod, ExpectedException(typeof(SpecificExceptionToCatch),
"Expected SpecificExceptionToCatch, but none was thrown.")]
public void TestForExceptionBetter()
{
MyClass.MethodThatThrowsException();
}