JUnit测试异常

假如需要测试下面的类:

public class Student {
  public boolean canVote(int age) {
      if (i<=0) throw new IllegalArgumentException("age should be +");
      if (i<18) return false;
      else return true;
  }
}

测试抛出的异常有三种方法:

  1. @Test ( expected = Throwable.class )
@Test(expected = IllegalArgumentException.class)
public void canVoteExp() {
    Student student = new Student();
    student.canVote(0);
}

这种测试有一点误差,因为异常会在方法的某个位置被抛出,但不一定在特定的某行。

  1. ExpectedException
    如果要使用JUnit框架中的ExpectedException类,需要声明ExpectedException异常。

@Rule
public ExpectedException thrown = ExpectedException.none();

然后可以使用更加简单的方式验证预期的异常

@Test
public void canVoteExp() {
    Student student = new Student();
    thrown.expect(IllegalArgumentException.class);
    student.canVote(0);
}

还可以设置预期异常的属性信息

@Test
public void canVoteExp() {
    Student student = new Student();
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("age should be +");
    student.canVote(0);
}

这种方法可以更加精确的找到异常抛出的位置。

  1. try/catch with assert/fail
    在JUnit4之前的版本中,使用try/catch语句块检查异常
@Test
public void canVoteExp() {
    Student student = new Student();
    try {
        student.canVote(0);
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), containsString("age should be +"));
    }
    fail("expected IllegalArgumentException for non + age");
}

尽管这种方法很老了,但是还是非常有效的。主要的缺点就是很容易忘记在catch语句块之后写fail()方法,如果预期异常没有抛出就会导致信息的误报。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容