你怎么断言在JUnit 4测试中抛出某个异常? [英] How do you assert that a certain exception is thrown in JUnit 4 tests?

查看:626
本文介绍了你怎么断言在JUnit 4测试中抛出某个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以惯用方式使用JUnit4来测试某些代码是否会抛出异常?



虽然我当然可以这样做:

  @Test 
public void testFooThrowsIndexOutOfBoundsException(){
boolean thrown = false;

试试{
foo.doStuff();
} catch(IndexOutOfBoundsException e){
thrown = true;
}

assertTrue(抛出);
}

我记得有一个注释或Assert.xyz或

解决方案

解决方案

> JUnit 4支持:

  @Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}

参考: https://junit.org/junit4/faq.html#atests_7


How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

  try {
    foo.doStuff();
  } catch (IndexOutOfBoundsException e) {
    thrown = true;
  }

  assertTrue(thrown);
}

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

解决方案

JUnit 4 has support for this:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);
}

Reference: https://junit.org/junit4/faq.html#atests_7

这篇关于你怎么断言在JUnit 4测试中抛出某个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆