模块化
写代码时, 写的很碎片
但不知道怎么回事最后拼在一起就运行起来了
电影拍摄与剪辑
电影拍摄的时候专心做拍摄的事情
剪辑的人负责将不同电影片段拼凑在一起
工具盒
制造的工具可以被别人使用
有时创建一系列工具, 组成工具盒, 别人并不会用到所有的工具
单元测试Unit Test
目的
确保模块的每个组件都是健康且正确的
三大步骤
准备:对象,参数
调用
检查:返回值,对象状态
测试方法 1
有些方法会 会有返回值
需要检测 返回值是否正确
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Driver { public static void main() { new Driver().run(); } public void run() { // 1. 准备 Fraction fraction = new Fraction(); fraction.setNominator(3); fraction.setDenominator(4); // 2. 调用 double value = fraction.value(); // 3. 检查 System.out.println(value); }}
测试方法 2
有些方法会更改对象状态(属性的值)
需要检测 属性是否正确
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Driver { public static void main() { new Driver().run(); } public void run() { // 1. 准备 Point point = new Point(3, 4); // 2. 调用 point.flip(); // 3. 检查 System.out.println(point.getX()); System.out.println(point.getY()); // 3+. or 借用安全的方法 检查 System.out.println(point.description()); }}
测试构造方法
需要确定调用后 对象的属性 是否正常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Driver { public static void main() { new Driver().run(); } public void run() { // 1 + 2. 准备 + 调用 Fraction fraction = new Fraction("3/4"); // 3. 检查 System.out.println(fraction.getNumerator()); System.out.println(fraction.getDenominator()); }}
测试的优先级
1. description()
2. 构造
3. 一般方法