這是專欄《SpringBoot自動(dòng)化單元測試教程》的第五篇文章。本文我們將討論JUnit5的參數(shù)化測試。
參數(shù)化測試可以使用不同的參數(shù)多次運(yùn)行測試。使用 @ParameterizedTest注解代替常規(guī)@Test注解到被測試方法上。此外,你必須聲明至少一個(gè)參數(shù)源,測試方法執(zhí)行時(shí)會(huì)使用這些測試源中的參數(shù)。
以下示例演示了一個(gè)參數(shù)化測試,該測試使用@ValueSource注解將String數(shù)組指定為參數(shù)源。
@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
void palindromes(String candidate) {
assertTrue(isPalindrome(candidate));
}
/**
* 判斷一個(gè)字符串是否為回文串
* @param str str
* @return boolean
*/
public static boolean isPalindrome(String str) {
if (str == null || str.length() == 0) {
throw new RuntimeException("字符串為空");
}
int mid = (str.length() - 1) / 2;
for (int i = 0; i <= mid; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
return false;
}
}
return true;
}
數(shù)據(jù)源中的各參數(shù)會(huì)依次進(jìn)行測試,執(zhí)行結(jié)果如下:
palindromes(String) ?
├─ [1] racecar ?
├─ [2] radar ?
└─ [3] able was I ere I saw elba ?
更多數(shù)據(jù)源配置:
| 示例輸入 | 結(jié)果參數(shù)列表 |
|---|---|
@CsvSource({ "apple, banana" }) |
"apple","banana"
|
@CsvSource({ "apple, 'lemon, lime'" }) |
"apple","lemon, lime"
|
@CsvSource({ "apple, ''" }) |
"apple",""
|
@CsvSource({ "apple, " }) |
"apple",null
|
@CsvSource(value = { "apple, banana, NIL" }, nullValues = "NIL") |
"apple", "banana",null
|
@CsvSource(value = { " apple , banana" }, ignoreLeadingAndTrailingWhitespace = false) |
" apple "," banana"
|