JUnit测试预期异常

在编写测试案例的时候,我们可能需要全量覆盖代码逻辑,当然也包含我们做的异常判断逻辑,此时我们就需要在JUnit中命中异常逻辑,但是测试结果还要是绿色通过的

1.通过给 @Test 传参实现,这种写法不够严谨,因为只能定位异常类型,不能定位到更精准的异常信息,代码片段如下:

@Test(expected= IndexOutOfBoundsException.class) 
  public void test1() { 
       new ArrayList<Object>().get(0);  
}

2.通过try-catch获取,可通过fail更精准的拿到不符合预期的结果,代码片段如下:

@Test
public test2() {
      try {
          new ArrayList<Object>().get(0);
          fail("没有命中你想要的错误");
      } catch (IndexOutOfBoundsException e) {
          assertThat(e.getMessage()).is("Index: 0, Size: 0");
      }  
}

3.通过JUnit提供的ExpectedException实现

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

@Test
public void test3() {
        List<Object> list = new ArrayList<Object>();
        thrown.expect(IndexOutOfBoundsException.class);
        thrown.expectMessage("Index: 0, Size: 0");
        list.get(0);  

发表回复

您的电子邮箱地址不会被公开。

5 × 1 =