開發(fā)人員常常使用單元測試來驗證的一段兒代碼的操作,很多時候單元測試可以檢查拋出預期異常( expected exceptions)的代碼。在Java語言中,JUnit是一套標準的單元測試方案,它提供了很多驗證拋出的異常的機制。本文探討一下他們的優(yōu)點。
我們拿下面的代碼作為例子,寫一個測試,確保canVote() 方法返回true或者false, 同時你也能寫一個測試用來驗證這個方法拋出的IllegalArgumentException異常。
public class Student {
public boolean canVote(int age) {
if (i<=0) throw new IllegalArgumentException("age should be +ve");
if (i<18) return false;
else return true;
}
}
。℅uava類庫中提供了一個作參數(shù)檢查的工具類--Preconditions類,也許這種方法能夠更好的檢查這樣的參數(shù),不過這個例子也能夠檢查)。
檢查拋出的異常有三種方式,它們各自都有優(yōu)缺點:
1.@Test(expected…)
@Test注解有一個可選的參數(shù),"expected"允許你設置一個Throwable的子類。如果你想要驗證上面的canVote()方法拋出預期的異常,我們可以這樣寫:
@Test(expected = IllegalArgumentException.class)
public void canVote_throws_IllegalArgumentException_for_zero_age() {
Student student = new Student();
student.canVote(0);
}
簡單明了,這個測試有一點誤差,因為異常會在方法的某個位置被拋出,但不一定在特定的某行。
2.ExpectedException
如果要使用JUnit框架中的ExpectedException類,需要聲明ExpectedException異常。
@Rule
public ExpectedException thrown= ExpectedException.none();
然后你可以使用更加簡單的方式驗證預期的異常。
@Test
public void canVote_throws_IllegalArgumentException_for_zero_age() {
Student student = new Student();
thrown.expect(NullPointerException.class);
student.canVote(0);
}
或者可以設置預期異常的屬性信息。
@Test
public void canVote_throws_IllegalArgumentException_for_zero_age() {
Student student = new Student();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("age should be +ve");
student.canVote(0);
}