JUnit5教程(5):JUnit5參數(shù)化測試

這是專欄《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"
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容