3. Testing
约 414 字大约 1 分钟
2025-04-16
这节课主要学两点:
- 选择排序
- 学习 TDD 开发(测试驱动开发)
选择排序
选择排序的步骤是:
- 先找到最小的元素
- 把这个最小的元素移动到数组最前面
- 对剩余的数组进行选择排序
TDD 开发
测试驱动开发,一般是先写测试类,然后写主要功能类。
先写一共 Sort 的测试类:
public class TestSort() {
public static void main(String[] args) {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input); // 这里就直接把要实现的函数功能声明好
org.junit.Assert.assertArrayEquals(expected, input);
}
}
然后我们再去实现 sort 函数。
public class Sort() {
/** Sorts strings destructively. */
private static void sort(String[] x, int start) {
int smallestIndex = findSmallest(x);
swap(x, start, smallestIndex);
sort(x, start + 1);
}
/** Returns the smallest string in x. */
public static String findSmallest(String[] x) {
int smallestIndex = 0;
for (int i = 0; i < x.length; i += 1) {
int cmp = x[i].compareTo(x[smallestIndex]);
if (cmp < 0) {
smallestIndex = i;
}
}
return smallestIndex;
}
}
TDD 思想
- 确定一个新功能。
- 为该功能编写一个单元测试。
- 运行测试。它应该失败。
- 编写通过测试的代码。
- 可选:重构代码以使其更快、更整洁等。
JUnit 使用方法
JUnit 函数
org.junit.Assert.assertEquals(expected, actual)
这个函数用来检测 expected 和 actual 是否一致。
JUnit 除了assertEquals方法之外还有很多这样的方法,比如assertFalse、assertNotNull、fail等等,并且它们可以在官方 JUnit 文档中找到。
JUnit 注解
- 在开头导包的时候加上
import org.junit.Test
和import static org.junit.Assert.*
,在每一个类前面加上@Test
- 将每个测试方法改为非静态。
- 从TestSort类中删除我们的main方法。