3

在一个 junit 类中,我想测试是否引发了异常,如果没有,提供一条解释性消息,建议在测试失败时要查找的内容。所以,像...

    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()");

显然,没有failureMessage()这样的方法。我不可能是世界上唯一一个想要实现失败消息的人。我在搜索的任何地方都没有找到示例。

请注意,这是参考 Junit4 @Rule 和 ExpectedException 功能。

4

2 回答 2

2

JUnit 4.12 支持自定义失败消息(请参阅发行说明)。如果您的测试没有引发预期的异常,则使用此失败消息。Hamcrest 匹配器处理错误消息等其他所有内容。

JUnit 4.12 于 2014 年 12 月 4 日发布。

于 2013-11-27T21:35:40.980 回答
1

您可以使用自定义Matcher的子类BaseMatcher覆盖toString()来做您想做的事。

于 2013-11-27T20:33:14.563 回答