การทดสอบใน Java เบื้องต้น
Maria Milusheva
Senior Software Engineer
ที่ผ่านมาเราเขียนเทสหลังจากเขียน production code เสมอ
TDD ทำโดยเขียนเทสก่อนเขียน production code
ทำไมต้องใช้ TDD?
1. ต้องเขียนเทสที่ล้มเหลวก่อนเขียน production code ใดๆ
2. ต้องเขียนเทสที่สั้นที่สุดเท่าที่เป็นไปได้
3. ต้องไม่เขียน production code มากกว่าที่จำเป็นสำหรับผ่านเทส
ทำตามลำดับนี้ = หนึ่งรอบของ TDD
การพัฒนาเกิดขึ้นผ่านการทำรอบ TDD ซ้ำๆ
สมมติว่าต้องการเขียนเมธอดที่ตรวจสอบว่า integer เป็น palindrome หรือไม่
ตัวอย่าง palindromic integer: 12321, 0, 3333
@Test
public void isPalindrome_nonPalindromicInt_returnsFalse() {
int number = 1234;
assertFalse(isPalindrome(number)); // isPalindrome() is not yet written
}
เทสเปรียบเสมือนบันทึกที่ฝากไว้ให้ตัวเองในอนาคต เพื่อเตือนให้ระลึกถึง requirement ของโปรเจกต์
public boolean isPalindrome(int num) {
return false; // Write minimal code that fulfills the requirements of the test.
}
เทสผ่านแล้ว พร้อมไปยังรอบถัดไปของ TDD
เทสใหม่ — requirement ใหม่ของฟีเจอร์:
@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 เหมาะมากสำหรับการแก้บัก!
เมธอดที่เพิ่งเขียนคืนค่า true สำหรับ number = -121 ซึ่งไม่ถูกต้อง!
เขียน unit test เพื่อแสดงให้เห็นบักนี้:
@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 เบื้องต้น