3

In a junit class, I want to test that an exception is thrown, and if not, provide an explanatory message suggesting what to look for if the test fails. So, something like...

    thrown.expect(UnsupportedOperationException.class);
    thrown.expectMessage("an exception message");
    thrown.failureMessage("This method should not be called directly. Be sure to use a subclass or mock that implements the method foo()");

Obviously, there is no such method failureMessage(). I cannot be the only one in the world who has ever wanted to implement a failure message. I have not found an example anywhere in my searches.

Note that this is in reference to the Junit4 @Rule and ExpectedException features.

Bill Turner
  • 869
  • 1
  • 13
  • 27

2 Answers2

2

JUnit 4.12 has support for custom failure messages (see release notes). This failure message is used if your test does not throw an expected exception. Everything else like wrong messages is handled by Hamcrest matchers.

JUnit 4.12 was released 2014-12-04.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
1

You can use a custom Matcher, subclassing BaseMatcher overriding toString() to do what you want.

Kevin Welker
  • 7,719
  • 1
  • 40
  • 56
  • Thanks, Kevin. I will have to dig into writing my own custom matcher, I guess. I was hoping to avoid that. I will not mark this as the correct answer for a few days just to be sure someone else doesn't come along with a different solution. – Bill Turner Nov 27 '13 at 20:35