The testng trace Exception Handling Code provides an option. You can test whether the code throws an exception or does not throw the exception. @ Test annotation expectedexceptions parameters are used together. Now let's take a look at the @ test (expectedexceptions) action.
Create a class
/** This class prints the given message on console.*/public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public void printMessage(){ System.out.println(message); int a =0; int b = 1/a; } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } }
Create test case class
Create a Java class file named expectedexceptiontest. Java in c: \> testng_workspace
import org.testng.Assert;import org.testng.annotations.Test;public class ExpectedExceptionTest { String message = "Manisha"; MessageUtil messageUtil = new MessageUtil(message); @Test(expectedExceptions = ArithmeticException.class) public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); messageUtil.printMessage(); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Manisha"; Assert.assertEquals(message,messageUtil.salutationMessage()); }}
Create test run
Create testng. xml and run the test case in c: \> testng_workspace.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" ><suite name="Suite1"> <test name="test1"> <classes> <class name="ExpectedExceptionTest" /></classes> </test></suite>
Compile the messageutil test case class using javac
C:\TestNG_WORKSPACE>javac MessageUtil.java TestJunit.java
Now, run the test run, which runs the test cases defined in the provided test case class.
C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml
Verify the output. Testprintmessage () will pass the test.
Inside testPrintMessage()ManishaInside testSalutationMessage()Hi!Manisha===============================================Suite1Total tests run: 2, Failures: 0, Skips: 0===============================================
Testng exception test [go]