This is a consequence of the fact that exceptions are expected in a unit case.

What is traditional testing design pattern to do Expectedexception test?

package com.asjava;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.List;

public class TestNGExpectedExceptionTest extends Assert {

    @Test
    public void testNullPointerException() {
        try {
            List list = null;
            int size = list.size();
            fail("The test should have failed");
        } catch (NullPointerException e) {
            // success, do nothing: the test will pass
        }
    }
}

This is somehow popular testing design pattern in the past, it reverse logic (“pass if an exception is thrown, fail when all goes well”).

The new – to use annotation Expectedexception.

package com.asjava;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.List;

public class TestNGExpectedExceptionTest extends Assert {

    @Test(expectedExceptions = NullPointerException.class)
    public void testNullPointerException() {
        List list = null;
        int size = list.size();
    }
}

ExpectedExceptions is an attribute of annotation @Test, it is an array of classes that contains a set of exception classes expected to be thrown in this test method.

Ideally If there have no exception or an unexpected exception which is not being listed in the attribute is thrown, TestNG engine will mark the test method as a failure. In the way you can benefit from the below:

  • Readable and understandable, when you read the test codes you immediately know what is supposed to happen and what expectedexception is desired.
  • It removes all the useless codes which was created by the try/catch/fail/ empty statement, thereby allowing the test method to focus purely on the business logic.

While the attribute expectedExceptions likely covers most of our needs for exception testing, the only disadvantage is that developers cannot assert error message of the exception object, in case the best practice is to declare a customized exception that will contain enough information for the code to be able to look up the string in the appropriate locale.