[Test-driven development 测试驱开发](https://zh.wikipedia.org/wiki/%E6%B5%8B%E8%AF%95%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91)是一种软件开发过程中的应用方法,以其倡导先写测试程序,然后编码实现其功能得名。在实际的使用过程中,笔者认为其优缺点如下: * [ ] 优点1:先写测试代码这强制的要求我们在完成功能实现前明确自己当前想要功能的输入与输出。 * [ ] 优点2:强制我们在正式动手开发前,在心中梳理代码的编写流程。 * [ ] 优点3:会提升我们对细节的把控能力。 * [ ] 缺点1:对编写者的编写技能要求较高。对于初学者而言,还停留在排查一些语法错误的阶段。而此时如果单元测试报错,初学者很难一下判断出是测试单元出了问题还是功能代码出了问题。 * [ ] 缺点2:对于初学者而言,会放慢其开发的速度。 * [ ] 缺点3:在编写测试时全凭想像,对开发经验、项目的全局掌握能力、抽象能力等均要求较高。 由于上述优缺点的存在,所以我们建议在实际应用TDD进行开发时应遵循以下几点开发原则: * [ ] 如果该功能有UI支持,在编写测试代码前应该先开发原型。 * [ ] 在编写测试代码前应该保障被测试主体已初始化。 * [ ] 在编写测试代码的过程中,应该遵循敏捷开发原则,即测试代码与功能交替进行迭代开发。 * [ ] 功能较复杂时,应该对复杂的功能进行拆解,分别对子功能进行测试开发。 按上述的原则,我们首先进行原型的开发,然后进行功能代码初始化,接着开发测试代码,最后在测试代码的协助下完成功能开发。 ## 原型开发 打开klass/index/index.component.html ``` <td> <a routerLink="./edit/{{klass.id}}">编辑</a>&nbsp;&nbsp; <button (click)="onDelete(klass)">删除</button> </td> ``` ## 功能代码初始化 klass/index/index.component.ts ``` /** * 删除班级 * @param klass 班级 */ onDelete(klass: Klass): void { } ``` ## 测试代码 编写测试代码就是我们整体思索功能实现的过程。在软件开发的过程考虑的因素有三:输入数据、输出数据及如何由输入数据得到输出数据。其实:输入数据与输出数据属于单元测试主要思索的问题,而如何由输入数据转换为输出数据则需要属于功能实现代码主要思索的问题。 | type | name | Description | sample | | --- | --- | --- | --- | | input | click | 点击删除按钮 | | | output | 发起http请求 | Delete /Klass/{id} | Delete /Klass/1 | 有了预期的输入与输出后,我们编写测试代码如下: klass/index/index.component.spec.ts ``` /** * 模拟返回班级列表 * 找到table中的第二行(第一行为表头)中的button元素 * 点击button元素 * 断言发起了预期的http请求 */ fit('测试删除按钮', () => { }); ``` 在注释中写代码编写流程的过程也就是在模拟我们进行代码编写的过程,这很有用(特别是处一些复杂操作时)!接下来,按注释的思路来完成代码: ``` /** * 模拟返回班级列表 * 找到table中的第二行(第一行为表头)中的button元素 * 点击button元素 * 断言发起了预期的http请求 */ fit('测试删除按钮', () => { const req = httpTestingController.expectOne('http://localhost:8080/Klass?name='); const klasses = [ new Klass(100, '计科1901班', new Teacher(1, 'zhagnsan', '张三')), ]; req.flush(klasses); fixture.detectChanges(); const htmlButtonElement: HTMLButtonElement = fixture.debugElement.query(By.css('table tr td button:first-of-type'➊)).nativeElement; expect(htmlButtonElement).toBeDefined();➋ htmlButtonElement.click(); const req1 = httpTestingController.expectOne('http://localhost:8080/Klass/100'); expect(req1.request.method).toEqual('DELETE'); req1.flush('', {status: 204, statusText: 'No Content'}); httpTestingController.verify(); ① }); ``` * ➊ 通过CSS选择器,选择table中的tr中的td中的第一个button按钮。 * ➋ 断言找到了此按钮(以防止前面的CSS接写错误)。 * ① 没有发生预期以外的http请求 #### 测试结果 ``` Chrome 78.0.3904 (Mac OS X 10.13.6) IndexComponent 测试删除按钮 FAILED Error: Expected one matching request for criteria "Match URL: http://localhost:8080/Klass/100", found none. ``` ## 功能开发 在编写测试的同时我们已经将输入与输出梳理的很清晰了,接下来的功能开发就显得简单了。 klass/index/index.component.ts ``` /** * 删除班级 * @param klass 班级 */ onDelete(klass: Klass): void { this.httpClient.delete(`http://localhost:8080/Klass/${klass.id}`) .subscribe(() => { alert('删除成功'); }); } ``` ## 完美化 点击删除按钮并删除成功后,我们希望在班级列表中同时移除该条记录。实现该功能的方法最少有两种解决方案:①删除成功后调用`ngOnInit`重新拉取后台数据;②删除成功的同时,直接将其由C层的班级列表`klasses`属性中移除; ### ① 重新加载 ``` /** * 删除班级 * @param klass 班级 */ onDelete(klass: Klass): void { this.httpClient.delete(`http://localhost:8080/Klass/${klass.id}`) .subscribe(() => { this.ngOnInit(); }); } ``` #### 测试 ``` Chrome 78.0.3904 (Mac OS X 10.13.6) IndexComponent 测试删除按钮 FAILED Error: Expected no open requests, found 1: GET http://localhost:8080/Klass ``` 该异常是由`httpTestingController.verify();`发出的。当执行`httpTestingController.verify();`时如果还有http请求没有被我们手动获取,则会发生异常。 由于我们在删除成功后执行了`ngOnInit()`,而此方法会重新发起后台访问,进而生成了一个新的http请求。所以在`httpTestingController.verify();`时发生了异常。 修正如下: ``` req1.flush('', {status: 204, statusText: 'No Content'}); httpTestingController.expectOne('http://localhost:8080/Klass?name='); ①✚ httpTestingController.verify(); ``` * ① 删除成功后又发起了一次初始化请求 ### ② 由数组中移除 ``` /** * 删除班级 * @param klass 班级 */ onDelete(klass: Klass): void { this.httpClient.delete(`http://localhost:8080/Klass/${klass.id}`) .subscribe(() => { this.klasses.forEach((inKlass, key) => { ① if (klass === inKlass) { this.klasses.splice(key, 1); ② } }); }); } ``` * ① 遍历教室数组 * ② 遍历到当前删除的教室时,将其由数组中移出 #### 测试 ``` req1.flush('', {status: 204, statusText: 'No Content'}); /*重新获取table中数据,断言table只有表头(行数为1)*/ fixture.detectChanges(); const htmlTableElement: HTMLTableElement = fixture.debugElement.query(By.css('table')).nativeElement; expect(htmlTableElement.rows.length).toBe(1); httpTestingController.verify(); ``` # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.6.1](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.6.1) | - | | CSS选择器:first-of-type | [https://www.runoob.com/cssref/sel-first-of-type.html](https://www.runoob.com/cssref/sel-first-of-type.html) | 5 | | Test-driven development 测试驱开发 | [Test-driven development 测试驱开发](https://zh.wikipedia.org/wiki/%E6%B5%8B%E8%AF%95%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91) | 10 | | jasmine null check | [https://www.tutorialspoint.com/jasminejs/jasminejs\_null\_check.htm](https://www.tutorialspoint.com/jasminejs/jasminejs_null_check.htm) | 5 | |HttpTestingController#verify | [https://www.angular.cn/api/common/http/testing/HttpTestingController#verify](https://www.angular.cn/api/common/http/testing/HttpTestingController#verify) | 5 |