unit-testing-5.0-导言-Mock与测试脆弱性

2026-05-21 ⏳0.4分钟(0.2千字)

Chapter 5 Mocks and test fragility

第 5 章 Mock 与测试脆弱性

仅个人学习使用,支持正版。

书名:Unit Testing: Principles, Practices, and Patterns

Chapter 4 introduced a frame of reference that you can use to analyze specific tests and unit testing approaches. In this chapter, you’ll see that frame of reference in action; we’ll use it to dissect the topic of mocks.

第 4 章介绍了一个参照框架,你可以用它来分析具体测试和单元测试方法。本章会看到这个框架如何发挥作用;我们将用它来剖析 mock 这个主题。

The use of mocks in tests is a controversial subject. Some people argue that mocks are a great tool and apply them in most of their tests. Others claim that mocks lead to test fragility and try not to use them at all. As the saying goes, the truth lies somewhere in between. In this chapter, I’ll show that, indeed, mocks often result in fragile tests—tests that lack the metric of resistance to refactoring. But there are still cases where mocking is applicable and even preferable.

在测试中使用 mock 是一个有争议的话题。有些人认为 mock 是很好的工具,并在大多数测试中使用它们。另一些人则认为 mock 会导致测试脆弱,因此尽量完全不用。俗话说,真相往往在中间。本章会说明,mock 确实经常导致脆弱测试,也就是缺乏抵抗重构能力的测试。但仍然存在一些适合使用 mock,甚至更应该使用 mock 的场景。

This chapter covers:

本章内容包括: