意外的異常是測試失敗,所以您既不需要也不想捕獲一個異常。
@Test
public void canConvertStringsToDecimals() {
String str = "1.234";
Assert.assertEquals(1.234, service.convert(str), 1.0e-4);
}
直到service
不會引發IllegalArgumentException
因爲str
中有一個小數點,這將是一個簡單的測試失敗。
預期的異常應該由@Test
的可選參數expected
參數處理。
@Test(expected=NullPointerException.class)
public void cannotConvertNulls() {
service.convert(null);
}
如果程序員又懶惰又扔Exception
,或者如果他有service
回報0.0
,會導致測試失敗。只有NPE
會成功。請注意,預期的異常的子類也適用。對於NPE
s這很少見,但與IOException
s和SQLException
s很相似。
在極少數情況下,您想要測試特定的異常消息,請使用新版ExpectedException
JUnit @Rule
。現在
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void messageIncludesErrantTemperature() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("-400"); // Tests that the message contains -400.
temperatureGauge.setTemperature(-400);
}
,除非setTemperature拋出IAE
和消息包含用戶試圖設定的溫度,則測試失敗。該規則可以以更復雜的方式使用。
你舉的例子可以最好地處理:
private void testNumber(String word, int number)
throws OutOfRangeNumberException {
assertEquals(word, service.convert(number));
}
@Test
public final void testZero()
throws OutOfRangeNumberException {
testNumber("zero", 0);
}
可以內嵌testNumber
;現在,它沒有多大幫助。你可以把它變成一個參數化的測試類。
的ExpectedException是測試預期的例外的首選方式。 –
我同意並且已經提出了Eric的回答。 – javadeveloper
如果您需要檢查異常的結構,則只需要ExpectedException。例如,CmisExceptions應該在它們內部設置一個特定的故障原因。我不得不編寫測試來檢查,並且爲此使用了Hamcrest匹配器。如果您只是期望出現異常,請將參數用於@Test。 –