Java 測試入門
Maria Milusheva
Senior Software Engineer
到目前為止,我們只是在產出程式碼之後才寫測試。
TDD 是先寫測試,再寫任何產出程式碼
為什麼要用 TDD?
1. 在寫任何產出程式碼前,必須先寫一個會失敗的測試
2. 必須寫出最短的測試
3. 產出程式碼只寫到足以讓測試通過為止,不多寫
依序套用以上規則=一次 TDD 循環
開發透過重複的 TDD 循環進行
假設我們要寫一個方法,檢查整數是否為回文
回文整數範例:12321、0、3333
@Test
public void isPalindrome_nonPalindromicInt_returnsFalse() {
int number = 1234;
assertFalse(isPalindrome(number)); // isPalindrome() is not yet written
}
測試就像留給未來自己的備忘錄,提醒專案需求。
public boolean isPalindrome(int num) {
return false; // Write minimal code that fulfills the requirements of the test.
}
測試現在通過。你可以進入下一個 TDD 循環。
新測試——此功能的新需求:
@Test
public void isPalindrome_PalindromicInt_ReturnsTrue() {
int number = 1234321; // Now write a more complex test case.
assertTrue(isPalindrome(number)); // At this point isPalindrome() will fail.
}
public boolean isPalindrome(int num) {
int inverted = 0;
while (num != 0) {
// At every iteration take the last digit of the number using % 10
// and add it to inverted * 10.
inverted = inverted * 10 + num % 10;
// Now that we have processed the last digit, discard it using / 10.
num = num / 10;
}
return inverted;
}
TDD 非常適合修補錯誤!
我們剛寫的方法對 number = -121 回傳 true。這不正確!
我們寫一個單元測試來重現此錯誤:
@Test
public void isPalindrome_NegativeNumber_ReturnsFalse() {
int number = -121; // Not a palindrome as -121 is not the same as 121-.
assertFalse(isPalindrome(number));
}
public boolean isPalindrome(int num) {
if (num < 0) {
return false; // We add a clause to return false for negative values.
}
int inverted = 0;
while (num != 0) {
inverted = inverted * 10 + num % 10;
num = num / 10;
}
return inverted;
}
Java 測試入門