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!
- 1Unclear what you mean; do you want to test the contents of the expected exception's error message?fge– fge2014-11-06 20:20:19 +00:00Commented Nov 6, 2014 at 20:20
- Yes, that is correct. That's exactly what I want.rickygrimes– rickygrimes2014-11-06 20:23:30 +00:00Commented Nov 6, 2014 at 20:23
- @fge - Can you please suggest?rickygrimes– rickygrimes2014-11-06 20:27:19 +00:00Commented Nov 6, 2014 at 20:27
Add a comment |
1 Answer
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...
1 Comment
Asaf
that should be
expectedExceptionsMessageRegExp