Javaによるテスト入門
Maria Milusheva
Senior Software Engineer
これまでは本番コードの後にテストを書いてきました。
TDDは本番コードより先にテストを書きます
TDDを行う理由
1. 本番コードを書く前に、失敗するテストを書く
2. 可能な限り短いテストを書く
3. テストを通すのに十分な最小限の本番コードだけを書く
これらを順に適用=TDDの1サイクル
開発は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によるテスト入門