TestNG expectedExceptions Attribute: In this post, we are going to understand how to use the testNG exception (expectedExceptions) with the @test method. TestNg provides a feature when a user can specify the type of exception that are expected to be thrown by a test method during execution. User can also mention multiple values. If the exception thrown by the test is not a part of the user entered list, then the test method will be marked as failed.
It is more important to test the positive and negative behavior of an application because if you do not deal with such a situation, your application has got terminated. So, in this case, you need to use this expectedExceptions so that your program will run smoothly.
Syntax:
Using expectedExceptions, we can handle any exception in a testNg program. We have to mention the type of exception with the .class.
expectedExceptions Attribute Example
@Test(expectedExceptions = { ArithmeticException.class }) @Test ( expectedExceptions = { IOException.class, NullPointerException.class } )
Let us try to understand the above concept with a simple example:
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>
As you see that the above testNG class we have not used the expectedExceptions in the program, thats why the test method got failed, but let us update the same class with the expectedExceptions attribute and run the same and see the output.
After modifying the class:
package softwareTestingMaterial; import org.testng.annotations.Test; public class TestNGException { @Test(expectedExceptions = ArithmeticException.class) public void testException() { System.out.println("SoftwareTestingo.com"); int i = 1 / 0; } }
Use the same testng.xml file to run the above TestNG class.
As you see, when we have used the expectedExceptions attribute with the @test method when the ArithmeticException is thrown by the @Test method. It will compare the expectedExceptions attribute value. If both the values matched, it will be handled by TestNg. That means your @Test method will be pass, and the remaining part of that method will be skipped.
You can get more TestNg tutorials by following the link, If you have any suggestions regarding then let us know in the comment section.
Source: link
Leave a Reply