Why does TestNG Allow Several Expected Exceptions?


TestNG supports multiple exceptions in single @Test method. It is similar to the catch exception in Java where user can mention multiple exception class those are possible to be thrown.

Ex: Syntax in catch exception is:

catch(IOException | InterruptedException ex) {

Similarly, syntax in TestNG is:

@Test(expectedExceptions={NullPointerException.class,IllegalArgumentException.class })
public void throwsNullPointer() {
    throw new NullPointerException();
}

One point to note that, in such scenarios, TestNG expects the one of the exceptions must be thrown from the list. If exception is different from the list or no exception, in such cases it fails the method. If exception is thrown as per the mentioned list method will be passed.

An example of error is as below if expected exception is not thrown:

Method throwsNullPointer()[pri:0, instance:OrderofTestExecutionInTestNG@3567135c] should have thrown an exception of any of types [class java.lang.NullPointerException, class java.lang.IllegalArgumentException]

In this article, we will illustrate possible reasons to support several exceptions in one Test method.

  • The very first reason is providing similar capability as catch statement in Java. It allows user to handle the exception at method level and can avoid try catch block in actual code.

  • Sometimes, code is complex and possible exceptions can be thrown in unique scenarios. To handle such scenarios, it is good to have functionality.

  • The one generic reason could be when testing multiple implementations of a feature which may behave differently based on provided input to thrown exceptions. The implementations could be different classes or different versions of the same class.

  • It is very useful when testing code depends on 3rd-party software and must be tested with multiple versions of the software. The different behaviour should be tested across the software using different data.

  • It is also useful when user needs to perform "black box" testing of an API or feature where the interface specification is unclear.

  • It is very handy when performing efficiency of code like unit tests those covers exception handling.

Updated on: 21-Aug-2023

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements