TestNG - Exception Test


TestNG provides a option of tracing the Exception handling of code. You can test whether a code throws desired exception or not. The expectedExceptions parameter is used along with @Test annotation. Now, let's see @Test(expectedExceptions) in action.

Create a Class

  • Create a java class to be tested say MessageUtil.java in C:\ > TestNG_WORKSPACE.

  • Add an error condition inside printMessage() method.

* This class prints the given message on console.
public class MessageUtil {

   private String message;

   //@param message to be printed
   public MessageUtil(String message){
      this.message = message; 

   // prints the message
   public void printMessage(){
      int a =0;
      int b = 1/a;

   // add "Hi!" to the message
   public String salutationMessage(){
      message = "Hi!" + message;
      return message;

Create Test Case Class

  • Create a java test class say ExpectedExceptionTest.java.

  • Add expected exception ArithmeticException to testPrintMessage() test case.

Create a java class file name 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()");     
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Manisha";

Create Test Runner

Create a testng.xml in C:\ > TestNG_WORKSPACE to execute Test case(s).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1">
   <test name="test1">
	      <class name="ExpectedExceptionTest" />

Compile the MessageUtil, Test case classes using javac

C:\TestNG_WORKSPACE>javac MessageUtil.java TestJunit.java

Now, run the Test Runner, which will run test cases defined in provided Test Case class.

C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml

Verify the output. testPrintMessage() test case will be passed.

Inside testPrintMessage()
Inside testSalutationMessage()

Total tests run: 2, Failures: 0, Skips: 0