Junit ExpectedException失败,带有解释性消息

时间:2013-11-27 19:56:58

标签: java junit expected-exception

在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功能。

2 个答案:

答案 0 :(得分:2)

JUnit 4.12支持自定义失败消息(请参阅release notes)。如果您的测试没有抛出预期的异常,则使用此失败消息。 Hamcrest匹配器处理其他所有错误信息。

JUnit 4.12于2014-12-04发布。

答案 1 :(得分:1)

您可以使用自定义Matcher,继承BaseMatcher重写toString()来执行您想要的操作。

相关问题