wip-1.0

2026-06-05 ⏳0.8分钟(0.3千字)

Chapter 1 The goal of unit testing

第 1 章 单元测试的目标

This chapter covers:

本章内容包括:

Learning unit testing doesn’t stop at mastering the technical bits of it, such as your favorite test framework, mocking library, and so on. There’s much more to unit testing than the act of writing tests. You always have to strive to achieve the best return on the time you invest in unit testing, minimizing the effort you put into tests and maximizing the benefits they provide. Achieving both things isn’t an easy task.

学习单元测试,并不会止步于掌握它的技术细节,例如你喜欢的测试框架、mock 库等等。单元测试远不只是“写测试”这个动作。你始终需要努力让投入到单元测试中的时间获得最佳回报:尽量减少花在测试上的成本,同时最大化测试带来的收益。要同时做到这两点并不容易。

It’s fascinating to watch projects that have achieved this balance: they grow effortlessly, don’t require much maintenance, and can quickly adapt to their customers’ ever-changing needs. It’s equally frustrating to see projects that failed to do so. Despite all the effort and an impressive number of unit tests, such projects drag on slowly, with lots of bugs and upkeep costs.

看到那些达到这种平衡的项目会很令人着迷:它们增长得很自然,不需要太多维护,并且能够快速适应客户不断变化的需求。同样令人沮丧的是看到那些没能做到这一点的项目。尽管投入了大量精力,也拥有数量可观的单元测试,这些项目仍然进展缓慢,伴随着大量缺陷和维护成本。

That’s the difference between various unit testing techniques. Some yield great outcomes and help maintain software quality. Others don’t: they result in tests that don’t contribute much, break often, and require a lot of maintenance in general.

这正是不同单元测试技术之间的差异。有些技术能带来很好的结果,并帮助维持软件质量。另一些则不能:它们会产出贡献不大、经常失败、总体上需要大量维护的测试。

What you learn in this book will help you differentiate between good and bad unit testing techniques. You’ll learn how to do a cost-benefit analysis of your tests and apply proper testing techniques in your particular situation. You’ll also learn how to avoid common anti-patterns—patterns that may make sense at first but lead to trouble down the road.

你将在本书中学到的内容,会帮助你区分好的和坏的单元测试技术。你会学会如何对测试做成本收益分析,并在自己的具体场景中应用合适的测试技术。你还会学会如何避免常见反模式——这些模式一开始可能看起来合理,但后续会带来麻烦。

But let’s start with the basics. This chapter gives a quick overview of the state of unit testing in the software industry, describes the goal behind writing and maintaining tests, and provides you with the idea of what makes a test suite successful.

不过我们先从基础开始。本章会快速概览软件行业中单元测试的现状,说明编写和维护测试背后的目标,并让你理解什么样的测试套件才算成功。