Reputation: 2716
I referred the below link - http://www.mkyong.com/unittest/testng-tutorial-2-expected-exception-test/ to test exceptions using TestNG. How do I print the message from the calling method? For eg, when orderBo.save(null);
is called, how do I print - Order is empty!
Upvotes: 3
Views: 4542
Reputation: 121820
You can use, along the expectedExceptions
parameter to the @Test
annotation, the expectedExceptionsMessageRegEx
. However, this becomes quite a messy annotation:
@Test(
expectedExceptions = MyException.class,
expectedExceptionsMessageRegEx = "^regex for message here$"
)
public void testWhatever()
{
codeThatRaisesSomeException();
}
And note that the parameter value, as the parameter name suggests, is a regular expression...
Rather than that, why not just do this:
@Test
public void testWhatever()
{
try {
codeThatRaisesSomeException();
fail("No exception thrown!");
catch (MyException e) {
assertEquals(e.getMessage(), "the expected message here");
}
}
Ultimately, that is a matter of tastes; yours truly finds the latter more readable...
Upvotes: 8