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 테스트 소개