为了账号安全,请及时绑定邮箱和手机立即绑定

如何断言在JUnit 4测试中抛出某个异常?

如何断言在JUnit 4测试中抛出某个异常?

烙印99 2019-06-14 16:04:31
如何断言在JUnit 4测试中抛出某个异常?如何使用JUnit 4来习惯地测试某些代码抛出异常?我当然可以这样做:@Testpublic void testFooThrowsIndexOutOfBoundsException() {   boolean thrown = false;   try {     foo.doStuff();   } catch (IndexOutOfBoundsException e) {     thrown = true;   }   assertTrue(thrown);}我记得有注释或Assert.xyz或某物对于这类情况,这要少得多,更多的是JUnit的精神。
查看完整描述

3 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

编辑既然JUnit 5已经发布,最好的选择就是使用Assertions.assertThrows()(见我的另一个答案).

如果尚未迁移到JUnit 5,但可以使用JUnit 4.7,则可以使用ExpectedException规则:

public class FooTest {
  @Rule
  public final ExpectedException exception = ExpectedException.none();

  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    exception.expect(IndexOutOfBoundsException.class);
    foo.doStuff();
  }}

这比@Test(expected=IndexOutOfBoundsException.class)因为如果IndexOutOfBoundsException在此之前抛出foo.doStuff()

看见这篇文章详情


查看完整回答
反对 回复 2019-06-14
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

小心使用预期异常,因为它只断言方法抛出那个例外,而不是一个特定代码行在测试中。

我倾向于将其用于测试参数验证,因为此类方法通常非常简单,但更复杂的测试最好使用:

try {
    methodThatShouldThrow();
    fail( "My method didn't throw when I expected it to" );} catch (MyException expectedException) {}

作出判断。


查看完整回答
反对 回复 2019-06-14
  • 3 回答
  • 0 关注
  • 3556 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号