unit-testing-4.3-快速反馈与可维护性
zero4.3 The third and fourth pillars: Fast feedback and maintainability
4.3 第三和第四大支柱:快速反馈与可维护性
仅个人学习使用,支持正版。
书名:Unit Testing: Principles, Practices, and Patterns
In this section, I talk about the two remaining pillars of a good unit test:
本节会讨论优秀单元测试剩下的两个支柱:
- Fast feedback
快速反馈。 - Maintainability
可维护性。
As you may remember from chapter 2, fast feedback is an essential property of a unit test. The faster the tests, the more of them you can have in the suite and the more often you can run them.
你可能还记得第 2 章提到过,快速反馈是单元测试的一个基本属性。测试越快,测试套件中能够包含的测试就越多,你也能越频繁地运行它们。
With tests that run quickly, you can drastically shorten the feedback loop, to the point where the tests begin to warn you about bugs as soon as you break the code, thus reducing the cost of fixing those bugs almost to zero. On the other hand, slow tests delay the feedback and potentially prolong the period during which the bugs remain unnoticed, thus increasing the cost of fixing them. That’s because slow tests discourage you from running them often, and therefore lead to wasting more time moving in a wrong direction.
有了运行快速的测试,你可以大幅缩短反馈循环,甚至让测试在你刚刚破坏代码时就提醒你存在缺陷,从而几乎把修复这些缺陷的成本降为零。另一方面,慢速测试会延迟反馈,并可能延长缺陷未被发现的时间,从而增加修复成本。这是因为慢速测试会降低你频繁运行它们的意愿,进而让你在错误方向上浪费更多时间。
Finally, the fourth pillar of good units tests, the maintainability metric, evaluates maintenance costs. This metric consists of two major components:
最后,优秀单元测试的第四大支柱,也就是可维护性指标,用来评估维护成本。这个指标由两个主要部分组成:
- How hard it is to understand the test — This component is related to the size of the test. The fewer lines of code in the test, the more readable the test is. It’s also easier to change a small test when needed. Of course, that’s assuming you don’t try to compress the test code artificially just to reduce the line count. The quality of the test code matters as much as the production code. Don’t cut corners when writing tests; treat the test code as a first-class citizen.
理解测试有多难——这个部分与测试的大小有关。测试中的代码行数越少,测试就越容易阅读。需要修改时,小测试也更容易改。当然,前提是你不是为了减少行数而人为压缩测试代码。测试代码的质量和生产代码同样重要。写测试时不要偷工减料;要把测试代码视为一等公民。 - How hard it is to run the test — If the test works with out-of-process dependencies, you have to spend time keeping those dependencies operational: reboot the database server, resolve network connectivity issues, and so on.
运行测试有多难——如果测试会使用进程外依赖,你就必须花时间确保这些依赖可用:重启数据库服务器、解决网络连接问题,等等。