《Software Engineering at Google》摘抄(13)

by kevin 20. 十月 2022 18:27 >

Writing testable code requires an upfront investment. It is especially critical early in the lifetime of a codebase because the later testability is taken into account, the more difficult it is to apply to a codebase. Code written without testing in mind typically needs to be refactored or rewritten before you can add appropriate tests.(编写可测试代码需要前期投入。在代码库生命周期的早期,这一点尤其重要,因为越晚考虑可测试性,就越难应用到代码库中。在没有考虑到测试的情况下编写的代码通常需要重构或重写,然后才可以添加适当的测试。)

Preferring real implementations in tests is known as classical testing. There is also a style of testing known as mockist testing, in which the preference is to use mocking frameworks instead of real implementations. Even though some people in the software industry practice mockist testing (including the creators of the first mocking frameworks), at Google, we have found that this style of testing is difficult to scale. It requires engineers to follow strict guidelines when designing the system under test, and the default behavior of most engineers at Google has been to write code in a way that is more suitable for the classical testing style.(在测试中更倾向于使用真实实现被称为经典测试。还有一种测试风格被称为模拟测试,其中倾向于使用模拟框架而不是真实实现。尽管软件行业的一些人在进行模拟测试(包括第一个模拟框架的创造者),但在谷歌,我们发现这种测试风格很难扩展。它要求工程师遵循设计被测系统时的严格准则,而谷歌大多数工程师的默认行为是以一种更适合经典测试风格的方式来编写代码。)

To reduce the number of fakes that need to be maintained, a fake should typically be created only at the root of the code that isn’t feasible for use in tests. For example, if a database can’t be used in tests, a fake should exist for the database API itself rather than for each class that calls the database API.(为了减少需要维护的伪造测试代码的数量,伪造测试代码通常应该只在测试中不可行的代码根处创建。例如,如果一个数据库不能在测试中使用,那么应该为数据库API本身编写一个伪造测试,而不是为调用数据库API的每个类编写。)

  • 真实实现应优先于测试替代。

  • 如果在测试中不能使用真实实现,那么伪造实现通常是理想的解决方案。

  • 过度使用打桩会导致测试不明确和变脆。

  • 在可能的情况下,应避免交互测试:因为交互测试会暴露被测系统的实现细节,所以会导致测试不连贯。

分享到: 更多