views:

47

answers:

3

I'd like to write a TestNG test to make sure an exception is thrown under a specific condition, and fail the test if the exception is not thrown. Is there an easy way to do this without having to create an extra boolean variable?

A related blog post on this subject: http://konigsberg.blogspot.com/2007/11/testng-and-expectedexceptions-ive.html

+1  A: 

Why don't you use the try/fail/catch pattern mentioned in the blog post you linked to?

Thomas Lötzer
When I initially saw it, it seemed awkward to me. Now that I've experimented, it seems like it should actually work for what I'm trying to do.
Christopher Parker
+1  A: 
Vineet Reynolds
Check out the article Christopher linked to. That article explains what is wrong with it. Basically it is that you don't know where the expected exception was thrown.
Thomas Lötzer
@Thomas, thanks. I had to read it once again to see why.
Vineet Reynolds
I'm still pretty new to unit-testing, so I was unaware of the concept of guard assertions. Thanks for the link!
Christopher Parker
+1  A: 

@Test(expectedExceptions) is useful for the most common cases:

  • You expect a specific exception to be thrown
  • You need the message of that exception to contain specific words

Here are a few scenarios where @Test(expectedExceptions) is not sufficient:

  • Your test method has several statements and only one of them is expected to throw
  • You are throwing your own type of exception and you need to make sure it matches a certain criterion

In such cases, you should just revert to the traditional (pre-TestNG) pattern:

try {
  // your statement expected to throw
  fail();
}
catch(<the expected exception>) {
  // pass
}
Cedric Beust