有兩種方法:測試
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"); }