Expected Exceptions in TestNG

· Read in about 1 min · (212 words) ·

All exceptions are not bad in our product, means we have to test and verify the exceptions in our product. The ExpectedException is a way of verifying that your code throws a specific exception.

Verifying that code completes normally is important, but making sure the logic behaves as expected in failure and unexpected situations are also important.

In TestNG, we have an attribute as expectedExceptions which needs to be added to our test where we have to verify the Exception as expected. This doesn’t affect your existing tests steps as it’s in the attribute.

How to Test exceptions:

Below example throw java.lang.NullPointerException Exception and It’s an expected exception but our test is marked as failures means we are not handling the exception as expected.

package com.tutorial.testng;

import org.testng.annotations.Test;

public class ExpectedExceptionTest {

    @Test()
    public void expectedExceptionTest() {
        String ptr = null;
        // This line of code throws NullPointerException
        ptr.equals("testng");
    }
}

exception-throwing-in-testng

With ExpectedExceptions attribute:

Now let’s fix our above test and mark our test as pass by handling an expected exception. We will add the new attribute to our test
@Test(expectedExceptions = java.lang.NullPointerException.class)

package com.tutorial.testng;

import org.testng.annotations.Test;

public class ExpectedExceptionTest {

    @Test(expectedExceptions = java.lang.NullPointerException.class)
    public void expectedExceptionTest() {
        String ptr = null;
        // This line of code throws NullPointerException
        ptr.equals("testng");
    }
}

expected-exception-test-in-testng