在Java中,如何使用JUnit验证抛出的异常?

在Java中,如何使用JUnit验证抛出的异常?,第1张

在Java中,如何使用JUnit验证抛出的异常?

在JUnit
4中,可以使用ExpectedException规则轻松完成此 *** 作。

这是来自javadocs的示例

// These tests all pass.public static class HasExpectedException {    @Rule    public ExpectedException thrown = ExpectedException.none();    @Test    public void throwsNothing() {        // no exception expected, none thrown: passes.    }    @Test    public void throwsNullPointerException() {        thrown.expect(NullPointerException.class);        throw new NullPointerException();    }    @Test    public void throwsNullPointerExceptionWithMessage() {        thrown.expect(NullPointerException.class);        thrown.expectMessage("happened?");        thrown.expectMessage(startsWith("What"));        throw new NullPointerException("What happened?");    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5478543.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存