Test for exception in TestNG is easy. It is a manner of defining the correct annotation attributes. In the code below, a RuntimeException class is thrown with the message blabla. In the @Test annotation, you list all the exception class and the expected exception message. In this case, it is
@Test( expectedExceptions = { RuntimeException.class }, expectedExceptionsMessageRegExp = "blabla" )
Here is the complete code.
import org.testng.annotations.Test; public class TestException { @Test(description = "Test catching exception", expectedExceptions = { RuntimeException.class }, expectedExceptionsMessageRegExp = "blabla") public void testException() { try { throw new RuntimeException("blabla"); } finally {// Don't catch(){}. Otherwise TestNG will not catch it. Just do finally{}. // Clean up code here. } } }
Output
Github
- https://github.com/xuanngo2001/java-testng/blob/master/src/net/openwritings/testng/TestException.java