981
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();
}