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.

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top