我有一個函數在拋出無效輸入時拋出一個ParseException
,我想爲它編寫一個單元測試。此測試旨在確保在所有無效輸入上引發異常。 (對於這個問題,只是假設,輸入被定義爲有效的,如果它有[
開始,用]
結束,沒有[
的或]
的任何地方都在裏面。)檢查junit中所有語句是否引發異常的最有效方法是什麼?
我現在有這測試:
@Test
public void invalidListFromatShouldFail() {
final String[] tests = {
"[[]",
"[]]",
"[] hi",
"hi",
"[h]i",
"[hi []",
"[[]]"
};
for(String toTest : tests) {
try {
ListUtil.parseList(toTest, TestEnum.class);
} catch (ParseException e) {
assertThat(e.getMessage(), startsWith(
"§cList format is invalid: It must start with " +
"'[' and end with ']', and not have any '['" +
" or ']' anywhere else in it."));
continue;
}
fail("Exception was not thrown for " + toTest + "!");
}
}
它的工作,但它似乎不正確的方式。我嘗試使用ExpectedException
,但代碼仍然立即退出。 (我想什麼是這樣的:
@Test
public void invalidListFromatShouldFail() throws ParseException {
expected.expect(ParseException.class);
expected.expectMessage(startsWith(
"§cList format is invalid: It must start with " +
"'[' and end with ']', and not have any '['" +
" or ']' anywhere else in it."));
ListUtil.parseList("[[]", TestEnum.class);
ListUtil.parseList("[]]", TestEnum.class);
//ECT...
}
但只測試的第一個值;如果我把一個fail()
在最後它仍然會成功,因爲發生異常)。
我的問題是:是否有更優雅的方式來編寫此測試,使用ExpectedException
或其他方法?
只需確認一下,使用內置的參數化亞軍,最終會多次運行相同的代碼?這些參數中只有一個功能需要運行多次。 (我可能應該自己試試這個)。 – Pokechu22 2014-09-29 20:53:36
使用方法非常相似,即:您編寫一個檢查單個輸入的方法,並且'Parameterized'運行器負責爲不同輸入運行此方法。你不必自己寫任何循環。與JUnitParams相比,將會有更多的代碼,但這個想法基本相同。然而,如果你想在你的類中使用幾個方法,一些參數化和一些非參數化方法採用不同的參數,JUnitParams比'Parameterized'使用起來要方便得多。 – 2014-09-29 21:15:02