15
Mar

Handling user defined exceptions with custom exception message in TestNG

During automation, we may have the need the method to raise a known exception with Userdefined exception message. i.e. it the said method throws known exception with specific exception message, we can mark it PASS. Without this feature, any exception thrown during TestNG method execution, will mark the test as failed.

Following code snippet demonstrates how to achieve this in TestNG

Step 1: Create custom exception class
—————————————

@SuppressWarnings(“serial”)
class InvalidAgeException extends Exception {
InvalidAgeException(String s) {
super(s);
}
}

Step 2: Create a TestNG Method which throws this custom exception
——————————————————————
import java.io.IOException;
import org.testng.annotations.Test;

public class MultipleGroups {

@Test(expectedExceptions = { InvalidAgeException.class }, expectedExceptionsMessageRegExp = “Pass Message test”)
public void exceptionTestOne() throws Exception {
throw new InvalidAgeException(“Pass Message test”);
}

@Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = “.* Message .*”)
public void exceptionTestTwo() throws Exception {
throw new IOException(“Pass Message test”);
}

@Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = “Pass Message test”)
public void exceptionTestThree() throws Exception {
throw new IOException(“Fail Message test”);
}

}

Output:
——–
PASSED: exceptionTestOne
PASSED: exceptionTestTwo
FAILED: exceptionTestThree
org.testng.TestException:
The exception was thrown with the wrong message: expected “Pass Message test” but got “Fail Message test”

Some of exceptions we can handle at run-time:

ArithmeticException
ArrayStoreException
ClassCastException
ConcurrentModificationException
EmptyStackException
IllegalArgumentException
IllegalParameterException
IllegalThreadStateException
NumberFormatException
IllegalMonitorStateException
IllegalPathStateException
IllegalStateException
IndexOutOfBoundsException
MissingResourceException
NegativeArraySizeException
NoSuchElementException
NullPointerException
SecurityException
SystemException
UnsupportedOperationException