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!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With