有两种方法:测试
1、使用ExpectedExceptionspa
仅在junit4.7以上支持。不只能够测试捕获到某异常,也能够测试异常message。code
使用例子以下:blog
@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"); }
注意事项:it
1. ExpectedException 必须是publicio
2、使用annotationclass
这个只能测存在异常,测不了异常messagetest
使用方法:exception
@Test(expected = Exception.class) public void testException() throws Exception { StringCalculator.calculate("-1,-1"); }