JUnit Tests and Debugging
Debugger Basics
讲解了如何使用debugger的基本功能,step into, step out, step over等等。
JUnit and Unit Testing
在单元测试中,我们需要用到JUnit方便我们编写测试用例。
需要导入如下库:
1 2
| import static org.junit.Assert.*; import org.junit.Test;
|
每一个测试方法形如:
1 2 3 4
| @Test public void testMethod() { assertEquals(<expected>, <actual>); }
|
Running JUnit Tests in IntelliJ (or another IDE)
这里通过打断点进入sum函数,把乘号修改为加号即可通过测试用例:
1 2 3
| public static int sum(int a, int b) { return a + b; }
|

Application: IntLists
Part A: IntList Iteration
addConstant(lst, 1);
是为list每个节点的value加1。
通过调试发现它的判断是否加1的依据是lst != null
,所以当lst
为空时就不会进行加1操作(也就是最后一个节点被忽略了)。
1 2 3 4 5 6 7
| public static void addConstant(IntList lst, int c) { IntList head = lst; while (head.rest != null) { head.first += c; head = head.rest; } }
|
修改为如下之后解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public static void addConstant(IntList lst, int c) { IntList head = lst; while (true) { if (head == null) { return; } head.first += c; if (head.rest != null) { head = head.rest; } else { break; } } }
|
注:这里我第一次修改之后,忘记考虑传入的list为空的情况了,需要注意一下。
Part B: Nested Helper Methods and Refactoring for Debugging
这里主要是教你尽量不要用嵌套函数来写代码,因为这样会导致debug不方便。尝试嵌套函数分开写在单独的每一行,这样更有助于debug.
Part C: Tricky IntLists!
这部分尝试教你如何去写单元测试,框架代码已经给出了一个示例,我们只要尝试模仿它写出更多即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Test public void testSquarePrimesSimple1() { IntList lst = IntList.of(14, 15, 16, 17, 18); boolean changed = IntListExercises.squarePrimes(lst); assertEquals("14 -> 15 -> 16 -> 289 -> 18", lst.toString()); assertTrue(changed); }
@Test public void testSquarePrimesSimple2() { IntList lst = IntList.of(0, 0, 0, 0, 0); boolean changed = IntListExercises.squarePrimes(lst); assertEquals("0 -> 0 -> 0 -> 0 -> 0", lst.toString()); assertFalse(changed); }
@Test public void testSquarePrimesSimple3() { IntList lst = IntList.of(3, 5, 7, 11, 13); boolean changed = IntListExercises.squarePrimes(lst); assertEquals("9 -> 25 -> 49 -> 121 -> 169", lst.toString()); assertTrue(changed); }
|
最后在Simple3
这里出错了,发现是在检测出第一个质数3并修改之后,便会直接跳出,没有改变其他质数。
把最后返回值这里的布尔逻辑改一下就好,return currElemIsPrime || squarePrimes(lst.rest);
-> return squarePrimes(lst.rest) || currElemIsPrime;