Exceptions tests in testng

Whenever the test method throws an Exception, test fails. But sometimes, we have requirement wherein certain exception is expected. TestNG allows us to test Exception using expectedExceptions parameter as show in below example. Below test will pass because it throws the expected exception – IndexOutOfBoundsException.
 
package org.softpost;

import org.testng.annotations.Test;

public class ExceptionTests {

    @Test(expectedExceptions = IndexOutOfBoundsException.class)
    public void testPrintMessage() {
        System.out.println("This test will pass only if " +
                "IndexOutOfBoundsException is thrown");
        throw new IndexOutOfBoundsException();

    }
}

Here is the output of above test.
 
[TestNG] Running:
C:UsersSagar.IdeaIC15system	emp-testng-customsuite.xml
This test will pass only if IndexOutOfBoundsException is thrown

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Web development and Automation testing

solutions delivered!!