TestNG Exception | TestNG Tutorial
TestNG Exception:
In this post, I will show how to use TestNG Exception (i.e., expectedExceptions) parameter along with the @Test annotation. TestNG provides an option of tracing the exception handling of code.
Firstly, we see a basic program without using TestNG Exception.
Created a java class, say, TestNGException.java and added an error condition in the method testException().
package softwareTestingMaterial; import org.testng.annotations.Test; public class TestNGException { @Test public void testException() { System.out.println("SoftwareTestingMaterial.com"); int i = 1 / 0; } }
testng.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="softwaretestingmaterial"> <test name="testngTest"> <classes> <class name="softwareTestingMaterial.TestNGException" /> </classes> </test> </suite>
Console Output:
[TestNG] Running: SoftwareTestingMaterial.com =============================================== Default suite Total tests run: 1, Failures: 1, Skips: 0 ===============================================
As you can see from the test results, testException()
method was marked as failed by TestNG during execution.
Now let’s see TestNG Exception in action.
Check below video to see “TestNG Exceptions”
Please be patient. The video will load in some time.
If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.
The expected exception to validate while running the below test is mentioned using the expectedExceptions attribute value while using the @Test annotation.
package softwareTestingMaterial; import org.testng.annotations.Test; public class TestNGException { @Test(expectedExceptions = ArithmeticException.class) public void testException() { System.out.println("SoftwareTestingMaterial.com"); int i = 1 / 0; } }
testng.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="softwaretestingmaterial"> <test name="testngTest"> <classes> <class name="softwareTestingMaterial.TestNGException" /> </classes> </test> </suite>
Console Output:
[TestNG] Running: SoftwareTestingMaterial.com =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 ===============================================
As you can see from the test results, testException()
method was marked as passed by TestNG during execution.
You could find the complete TestNG tutorial here.
If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.