expectedExceptionsMessageRegExp attribute of @Test

This post will discuss the expectedExceptionsMessageRegExp attribute of @Test annotation in TestNG.

What does this attribute do? According to the documentation –

If expectedExceptions was specified, its message must match the regular expression specified in this attribute.

So, this means we won’t be able to use this attribute without using expectedExceptions first. Please, read this post to learn more about the expectedExceptions attribute. Here expectedExceptionsMessageRegExp will use a regex (regular expression) to match the thrown exception message.

import java.io.IOException;
import org.testng.annotations.Test;

public class CodekruTest {

	// matching an empty regex string
	@Test(expectedExceptions = { IOException.class, ArithmeticException.class }, expectedExceptionsMessageRegExp = "")
	public void test1() throws IOException {
		System.out.println("test1 throwing an IOException");
		throw new IOException("");
	}

	// matching exact regex
	@Test(expectedExceptions = { IOException.class,
			ArithmeticException.class }, expectedExceptionsMessageRegExp = "codekru")
	public void test2() throws IOException {
		System.out.println("test1 throwing an IOException");
		throw new IOException("codekru");
	}

	// this test will fail as message do not match the regex
	@Test(expectedExceptions = { IOException.class,
			ArithmeticException.class }, expectedExceptionsMessageRegExp = "bye")
	public void test3() throws IOException {
		System.out.println("test1 throwing an IOException");
		throw new IOException("codekru");
	}

	// here used regex to match the thrown exception message
	@Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = "^Hi .*$")
	public void test4() throws Exception {
		throw new IOException("Hi Codekru test");
	}

}

Output –

test1 throwing an IOException
test1 throwing an IOException
test1 throwing an IOException
PASSED: test1
PASSED: test2
PASSED: test4
FAILED: test3
org.testng.TestException: 
The exception was thrown with the wrong message: expected "bye" but got "codekru"
	at org.testng.internal.ExpectedExceptionsHolder.wrongException(ExpectedExceptionsHolder.java:71)

So, here test3() failed because the exception message thrown doesn’t match the regex, and this is how we use the expectedExceptionsMessageRegExp attribute in TestNG. Please visit this link to learn more about the regular exception symbols.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Other @Test attributes
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *