Introduction to Testing in Java
Maria Milusheva
Senior Software Engineer
So far we have only written tests after writing production code.
TDD is done by writing tests before writing any production code
Why do TDD?
1. Must write a failing test before writing any production code
2. Must write the shortest test possible
3. Must not write more production code than is sufficient to make the test pass
Applying these in sequence = one cycle of TDD
Development happens through repeated cycles of TDD
Suppose we want to write a method that checks if an integer is a palindrome
Examples of palindromic integers: 12321, 0, 3333
@Test
public void isPalindrome_nonPalindromicInt_returnsFalse() {
int number = 1234;
assertFalse(isPalindrome(number)); // isPalindrome() is not yet written
}
A test is like a note we leave to our future selves that reminds us of the project requirements.
public boolean isPalindrome(int num) {
return false; // Write minimal code that fulfills the requirements of the test.
}
Test now passes. We can move on to the next cycle of TDD.
New test - new requirement for the feature:
@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 is great for fixing bugs!
The method we just wrote returns true for number = -121
. This is not correct!
We write a unit test to illustrate the bug:
@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;
}
Introduction to Testing in Java