什么是测试驱动开发?(TDD)

测试驱动开发简称 TDD,英文全称 Test Driven Development

  • 结对编程:一个写,一个看;另一个写,一个看

编写一个函数,返回小于给定 max 值的所有素数组成的数组。

public static int[] getPrimes(int max)

1、思考

任务分解

  • 边界条件:getPrimes(2)、getPrimes(0)、getPrimes(-1)
  • 正常输入:getPrimes(9)、getPrimes(17)、getPrimes(30)

2、运行失败

写一个测试用例,运行失败(Tests failed)

public class PrimeUtilTest {

@Test
public void testGetPrimesForeEmptyResult() {
int[] expected = {};

Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(2));
Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(0));
Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(-1));
}
}
public class PrimeUtil {
public static int[] getPrimes(int i) {
return null;
}
}

3、测试通过

just enough 代码 1,测试通过(Tests pass)

public class PrimeUtil {
public static int[] getPrimes(int max) {
if (max <= 2) {
return new int[]{};
}
return null;
}
}

just enough 代码 2,测试通过(Tests pass)

public class PrimeUtilTest {

@Test
public void testGetPrimesForeEmptyResult() {
int[] expected = {};

Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(2));
Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(0));
Assert.assertArrayEquals(expected, PrimeUtil.getPrimes(-1));
}

@Test
public void testGetPrimes() {

Assert.assertArrayEquals(new int[]{2, 3, 5, 7}, PrimeUtil.getPrimes(9));
Assert.assertArrayEquals(new int[]{2, 3, 5, 7, 11, 13}, PrimeUtil.getPrimes(17));
Assert.assertArrayEquals(new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}, PrimeUtil.getPrimes(30));
}
}
public class PrimeUtil {
public static int[] getPrimes(int max) {
if (max <= 2) {
return new int[]{};
} else {
int[] newArray = new int[max];
int size = 0, j = 0;
for (int i = 2; i < max; i++) {
for (j = 2; j < i / 2 + 1; j++) {
if (i % j == 0) {
break; // 结束内循环
}
}
if (j == i / 2 + 1) {
newArray[size++] = i;
}
}
newArray = Arrays.copyOf(newArray, size); // 去除数组中多余的数据
return newArray;
}
}
}
  • 判断是否为质数:当一个数 i 除以所有大于 2,小于 i / 2 + 1都不等于 0,那他就是质数。
  • 所有:遍历大于 2,小于 max的所有数,判断是否为质数。
  • 放入到数组中:通过判断此时的j 是否已经是最大值,即 j = i / 2 + 1

    4、重构

重构代码(Refactor)

public class PrimeUtil {
public static int[] getPrimes(int max) {
// 提前准备
if (max <= 2) {
return new int[]{};
}

int[] primes = new int[max];
int count = 0;
// 控制
for (int num = 2; num < max; num++) {
if (isPrime(num)) {
primes[count++] = num;
}
}
primes = Arrays.copyOf(primes, count);
return primes;

}

// 策略
private static boolean isPrime(int num) {
for (int i = 2; i < num / 2 + 1; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

常用断言

  • Assert.assertEquals(expected, actual);
  • Assert.assertTrue(condition);
  • Assert.assertFalse(condition);
  • Assert.assertNull(condition);
  • Assert.assertNotNull(object);
  • Assert.assertArrayEquals(expecteds, actuals);
  • Assert.fail();

总结

1、先写测试用例;2、根据测试用例去实现代码;3、重构代码

评论默认使用 ,你也可以切换到 来留言。