Junit 测试exception

有两种方法:

一、使用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");
    }
原文地址:https://www.cnblogs.com/hf-cherish/p/5610892.html