TestNG Exceptions - expectedExceptions, expectedExceptionsMessageRegExp With Examples

Sometimes we want to test our methods for exceptions. TestNG allows us to perform exceptions testing using expectedExceptions and expectedExceptionsMessageRegExp parameters of @Test annotation.

TestNG expectedExceptions

Let’s say we have a simple utility method for dividing two numbers.

We know that if we try to divide a number by 0, it will throw java.lang.ArithmeticException with message as / by zero.

Let’s write a TestNG Test class to test this exception scenario.

We get the following output when we execute above test class.

If we remove the expectedExceptions attribute from the @Test annotation, then our test case will fail with below message.

expectedExceptions takes value as class array, so below value will work fine too.

TestNG Test expectedExceptionsMessageRegExp

We can extend our test method to look for exception message too. Test annotation expectedExceptionsMessageRegExp uses regular expression. Let’s see few examples of how we can use it.

Above test method will pass only when ArithmeticException is thrown with the exact message as “/ by zero”.

Let’s change the message so that our test will fail.

Our test will fail with following console output.

Let’s see how we can use the regular exception when we are not sure of the exact message of exception.

This test will pass because the regex provided by us will match with the exception message being thrown.

By admin

Leave a Reply

%d bloggers like this: