Exception in TestNG:

 

  • Some scenarios where we need to verify that an exception is being made by the program during execution.
  • TestNG provides the user with a facility to test such scenarios by allowing them to specify the type of such findings, which are expected to be thrown by the test method during execution.
  • You can test whether a code throws a desired exception or not, the expected exception parameter is used with @Test annotation.
  • TestNG we use expectedException with @Test annotation and we need to specify the type of exceptions which can be thrown when executing test methods.

 

Syntax: Assign exception to method:

  • Using expectedExceptions we can handle any type of exception in TestNG program.
  • Provide type of Exception with .class using the help of expectedExceptions.

 

Example: Without exception handling:

  • Below program we can not use expectedExceptions so shows ArithmeticException in output.

Output:

 

Example: With Exception handling:

  • Below program we use expectedExceptions so does not shows any type of exception.
  • Below example with the help of expectedExceptions using ArithmeticException handle exception to prevent case fail.

Output:

 

Example : With and Without Exception in TestNG:

  • Below example with and without Exception handling.

Output:

Note:

  • When we execute the above code, the examination method will return dividedByZeroProgram1″ as “passed” as we are handling exceptions and the test method “dividedByZeroProgram2” as output “failed” with exception as ‘“java.lang.ArithmeticException: / by zero”.