TestNG Exception Test
While writing automation tests there can be certain scenarios where we need to verify that an exception is being thrown by the program during execution. TestNG provides a feature to test such scenarios by allowing the user to specify the type of exceptions that are expected to be thrown by a test method during execution. It supports multiple values being provided for verification. If the exception thrown by the test is not part of the user entered list, the test method will be marked as failed.
Will see a sample programs to test the expected exceptions:
Scenario 1: Here we will NOT handle the exception and will see the result:
import org.testng.annotations.Test; public class ExceptionTest { @Test() public void exceptionTestOne() { int i = 1/0; System.out.println("Value of i :" + i); } }
Now will execute the above program and see the result:
In the above program, the output is Failed and it will throw Arithmetic Exception as we can not divide anything by ZERO and it is not handled in the program.
Scenario 2: Here we will handle the exception and will see the result:
import org.testng.annotations.Test; public class ExceptionTest { @Test(expectedExceptions={ArithmeticException.class}) public void exceptionTesting() { int i = 1/0; System.out.println("Value of i :" + i); } }
Now will execute the above program and see the result:
In the above program the output is Passed and it will NOT throw any exception as we have handled the exception using expectedExceptions Test annotation attribute as we know that there may be a chance of failing the program because of divide by ZERO.
In this way we will handle the exceptions using expectedExceptions Test annotation attribute.