26
Dec

Handling Exceptions without using try/catch block with TestNG

Like any programming language, our test cases need to be sturdy and capable to handle unexpected conditions as much as possible. e.g. While creating a temp file on detachable storage, it might meet a condition of read/write error, device not ready and other exceptions which interrupts normal flow of tests.

TestNG supports exception handling via “expectedExceptions”. TestNG 5.10 then added the attribute expectedExceptionsMessageRegExp, which allows known exception handling without using try/catch block in your testcase as follow:

In order to design our cases for known and unknown exceptions we can design our testcases as follow

Step 1: Design testcases with expectedExceptions e.g.

@Test(groups = { “smoke”}, expectedExceptions = {IOException.class}, expectedExceptionsMessageRegExp = “.* Message .*”)
public void exceptionMethod1() throws Exception {
System.out.println(“Inside Exception Method where IOException with custom message is created..”);
throw new IOException(“Pass Message test”);
}

@Test(expectedExceptions = {IOException.class, ArrayIndexOutOfBoundsException.class, NullPointerException.class}, expectedExceptionsMessageRegExp = “.*is is my*”)
public void exceptionMethod2() throws Exception {
System.out.println(“Inside Exception Method 2..”);
throw new ArrayIndexOutOfBoundsException(“this is my message”);
}

Step 2: run the tests