(In contrast to mcottle's answer) Long answer: NO... most of the time
When you say that you expect a test to raise a particular exception, you will know when ANY line in that test raises that particular exception.
That's not quite the same thing as knowing that the method under test throws the exception.
If your test involves setting up an object or context (within the test, not within your framework's version of SetUp
), you might be better off wrapping the single line you actually want to test in a try/catch, possibly with a helper.
For instance,
public static class AssertHelper {
public delegate void Thunk();
public static void DoesNotThrow<T>(Thunk thunk, string message = "")
where T: Exception {
try {
thunk.Invoke();
} catch(T) {
Assert.Fail(message);
}
}
}
and then
[TestMethod]
public void assertHelperInAction() {
// Random setup stuff here that's too annoying to put in my SetUp
// method.
AssertHelper.DoesNotThrow<IllegalArgumentException>(() =>
{/* My random method under test */})
}
If this test fails, I know that my method under test threw the exception, and not something in the random setup stuff.
(You should try and avoid random setup stuff. Sometimes, it's easier to have some setup code in the test.)