Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExceptionHandling with TestNG

Tags:

java

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!

like image 734
rickygrimes Avatar asked Jan 01 '26 14:01

rickygrimes


1 Answers

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...

like image 103
fge Avatar answered Jan 03 '26 02:01

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!