What is Expected Exceptions in TestNG?
In TestNG, expected exceptions are used to verify that a method throws a specific exception during execution. This is useful when you're testing error-handling logic in your application.
If the specified exception is thrown, the test passes. If not (either no exception or a different one), the test fails.
Syntax:
You use expectedExceptions inside the @Test annotation:
@Test(expectedExceptions = ExceptionType.class) public void testMethod() { // code that should throw ExceptionType }
Example:
Let’s say you want to test whether a method throws an ArithmeticException when dividing by zero:
import org.testng.annotations.Test; public class ExpectedExceptionExample { @Test(expectedExceptions = ArithmeticException.class) public void testDivideByZero() { int result = 10 / 0; // This will throw ArithmeticException } @Test public void testNoException() { int result = 10 / 2; System.out.println("Result: " + result); // This will not throw an exception } }
Explanation:
testDivideByZero()is expected to throwArithmeticException. Since dividing by 0 does throw it, the test passes.testNoException()runs normally and also passes, as it's not expecting any exception.
Expected exceptions are useful for negative testing, such as:
Handling of null inputs
Invalid configurations
Divisions by zero
Custom business exceptions