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 测试入门