3

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!

3
  • 1
    Unclear what you mean; do you want to test the contents of the expected exception's error message? Commented Nov 6, 2014 at 20:20
  • Yes, that is correct. That's exactly what I want. Commented Nov 6, 2014 at 20:23
  • @fge - Can you please suggest? Commented Nov 6, 2014 at 20:27

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

that should be expectedExceptionsMessageRegExp

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.