有两种方法:

一、使用ExpectedException

仅在junit4.7以上支持。不仅可以测试捕获到某异常,也可以测试异常message。

使用例子如下:

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

    @Test
    public void shouldThrowExceptionWhenSumGivenOneNegativeNumber() throws Exception {
        exception.expect(Exception.class);
        exception.expectMessage(containsString("negatives not allowed"));
        exception.expectMessage(containsString("-1"));
        StringCalculator.calculate("-1,1");
    }

public static int calculate(String numbers) throws Exception {
       throw new Exception("negatives not allowed: -1");
    }

注意事项:

1. ExpectedException 必须是public

 

二、使用annotation

这个只能测存在异常,测不了异常message

使用方法:

@Test(expected = Exception.class)
    public void testException() throws Exception {
        StringCalculator.calculate("-1,-1");
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
猜你喜欢
  • 2021-07-26
  • 2021-11-04
  • 2021-11-26
相关资源
相似解决方案