Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top