Skip to content Skip to navigation
Check Our New Demo Website!

Exception Test in TestNG

In TestNG we use expectedException with @Test annotation and we need to specify the type of exceptions that are expected to be thrown when executing the test methods.

A below example which throws an exception called “ArithmeticException” when dividing two numbers with denominator value as 0.

@Test(expectedExceptions=ArithmeticException.class)
	public void dividedByZeroExample1(){
		int e = 1/0;
	}

If we remove the “(expectedException = ArithmeticException.class)”, it will return exception called “java.lang.ArithmeticException: / by zero”

@Test
	public void dividedByZeroExample2(){
		int e = 1/0;
	}

Example: We will combine the above two examples and execute to check the output of the program

import org.testng.annotations.Test;
public class TestNGExamples {
	
	@Test(expectedExceptions=ArithmeticException.class)
	public void dividedByZeroExample1(){
		int e = 1/0;
	}
	
	@Test
	public void dividedByZeroExample2(){
		int e = 1/0;
	}
}

When we execute the above code, the test method "dividedByZeroExample1" will return as “Passed” as we are handling the exceptions and the Test Method "dividedByZeroExample2" will return output as "Failed" with exception as '“java.lang.ArithmeticException: / by zero”

Please find the below output of the above program.
exception test in TestNG

Test Frameworks: 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.