Introduction
In this article, we would discuss the TestNG exception test example. While writing automation tests using TestNG there could be scenarios where we need to verify that a particular exception is being thrown by the test method during execution.
expectedExceptions clause
In the TestNG framework, we can specify the expected exceptions to @Test annotation using the attribute “expectedExceptions=”. We can specify the list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, the test method will be marked as the failure.
In the example, let us explore how the exception test works in the TestNG framework in detail with suitable code examples.
Code Example
package com.testingdocs.testng.sample; import org.testng.annotations.Test; public class TestNGExceptionExample { @Test(expectedExceptions = ArithmeticException.class) public void divideWithZeroWithException() { System.out.println("TestingDocs.com >>> Below line throws an exception!!") ; int i = 9/0; } }
As shown in the above example we have specified the “ArithmeticException.class” as expected exception as the line 9/0 would throw the ArithmeticException.ArithmeticException is thrown when an exceptional arithmetic condition has occurred. For example, an integer “divide by zero” throws an instance of this class.
Output :
TestingDocs.com >>> Below line throws an exception!!
PASSED: divideWithZeroWithException
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
We can also specify the below syntax with curly braces if we want to specify multiple exceptions:
@Test(expectedExceptions={ArithmeticException.class})
Now we will see what happens when the exceptions doesn’t match with @Test method and annotation list.
Code snippet
package com.testingdocs.testng.sample; import java.io.FileNotFoundException; import org.testng.annotations.Test; public class TestNGExceptionExample { @Test(expectedExceptions = ArithmeticException.class) public void noMatchExceptionTest() throws FileNotFoundException { throw new FileNotFoundException() ; } }
Output
The @Test method throws FileNotFoundException, whereas the annotation expects ArithmeticException.So, the test method fails.
FAILED: noMatchExceptionTest
java.io.FileNotFoundException
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
In conclusion, TestNG also supports multiple exceptions and exception messages as well. In the next post, we will further discuss the concepts in detail.
TestNG Tutorials on this website can be found at:
https://www.testingdocs.com/testng-framework-tutorial/
For more details on the TestNG Framework, visit the official website of TestNG at: