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
Create Test Runner xml in /work/testng/src to execute test case(s). Compile the MessageUtil, Test case classes using javac. Now, run the Test Runner, which will run test cases defined in the provided Test Case class. Verify the output.
The expectedExceptions Attribute Within @Test annotation, TestNG supports multiple exceptions being provided for verification using attribute expectedExceptions. If the exception thrown by the test is not part of the user entered list of exceptions, the test will be marked as failed.
All @After methods are guaranteed to run even if a Before or Test method throws an exception. as it doesn't matter exception has occurred or not this annotation is going to be executed.
Oct. 15, 13 · Java Zone · Interview. @Test Annotation provides an attribute “expectedExceptions” allowing the user to specify the type of exceptions that are expected to be thrown by a test method during execution. This is normally used when you are trying to test certain business use cases and validate input data.
@Test(expectedExceptions)
is useful for the most common cases:
Per the documentation a test will fail if no expectedException
is thrown:
The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.
Here are a few scenarios where @Test(expectedExceptions)
is not sufficient:
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 }
Use @Test
annotation to check expected exceptions.
@Test( expectedExceptions = AnyClassThatExtendsException.class, expectedExceptionsMessageRegExp = "Exception message regexp" )
Or if you don't want to check for exception message, only below is enough
@Test(expectedExceptions = AnyClassThatExtendsException.class)
In that way, you don't need to use ugly try catch block, just invoke you exception-thrower method inside the test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With