Alex Rivera | Logout

How do I use Assert to verify that an exception has been thrown with MSTest?

Asked 2009-06-01T05:01:53.873
981

How do I use Assert (or other Test class) to verify that an exception has been thrown when using MSTest/Microsoft.VisualStudio.TestTools.UnitTesting?

Edit
Report

2 Answers

285

Usually your testing framework will have an answer for this. (See the comments for this thread for examples, there's lots!) But if your framework isn't flexible enough, you can always do this:

try {
    somethingThatShouldThrowAnException();
    Assert.Fail(); // If it gets to this line, no exception was thrown
} catch (GoodException) { }

As @Jonas points out, this DOES NOT work for catching a base Exception:

try {
    somethingThatShouldThrowAnException();
    Assert.Fail(); // raises AssertionException
} catch (Exception) {
    // Catches the assertion exception, and the test passes
}

If you absolutely must catch Exception, you need to rethrow the Assert.Fail(). But really, this is a sign you shouldn't be hand-writing this; check your test framework for options, or see if you can throw a more meaningful exception to test for.

catch (AssertionException) { throw; }

You should be able to adapt this approach to whatever you like -- including specifying what kinds of exceptions to catch. If you only expect certain types, finish the catch blocks off with:

} catch (GoodException) {
} catch (Exception) {
    // not the right kind of exception
    Assert.Fail();
}
answered 2009-06-01T05:06:54.727
2

Check out nUnit Docs for examples about:

[ExpectedException( typeof( ArgumentException ) )]
answered 2009-06-01T05:10:14.270

Your Answer