TestNG - Test an exception

By xngo on June 23, 2019

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

TestNG Exception output

Github

  • https://github.com/xuanngo2001/java-testng/blob/master/src/net/openwritings/testng/TestException.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.