# 测试装置

测试装置（test harness）是指执行测试套件所需的驱动程序与测试替身的集合，以及负责组织、运行并报告这些测试的框架。<sup>[1](https://glossary.istqb.org/en_US/term/test-harness?exact_matches_first=true&syllabus_id=23)</sup> 在实践中，该术语涵盖测试运行器、为被测系统做准备与清理的 setup 和 teardown 代码、替代真实依赖的桩（stub）、伪件（fake）与模拟对象（mock），以及将结果转化为通过或失败信号的报告机制。ISTQB 标准词汇表的一个早期版本将其定义为“由执行测试套件所需的桩与驱动程序构成的测试环境”，这一表述强调为驱动那些无法独立运行的代码而专门编写的代码。<sup>[2](https://api.glossary.istqb.org/storage/help/R0uz58NqLzUz48LVUuyGSF76NFj4LHQazSs0GlNS.pdf)</sup>

| 关键事实 | 详情 |
|---|---|
| 标准定义 | “执行测试套件所需的驱动程序与测试替身的集合”（ISTQB 词汇表，第 2 版）<sup>[1](https://glossary.istqb.org/en_US/term/test-harness?exact_matches_first=true&syllabus_id=23)</sup> |
| 起源 | 肯特·贝克（Kent Beck）于 1994 年 10 月在《Smalltalk Report》上发表《简单 Smalltalk 测试：使用模式》，公布 SUnit 设计；xUnit 家族由此衍生<sup>[3](https://www.cambridge.org/core/books/kent-becks-guide-to-better-smalltalk/simple-smalltalk-testing/0D2F14E0129D5EF29E85D796A5B845FC)</sup> |
| 夹具使用情况 | 在一项针对开发者所编写测试的大规模研究中，43.1% 的测试类包含至少一个 setup 方法，16.2% 包含至少一个 teardown 方法（包括自定义或继承而来）<sup>[4](https://doi.org/10.1145/3786583.3786857)</sup> |
| setup 中的模拟 | 同一数据集中，9.8% 的测试在测试 setup 方法中含有模拟代码<sup>[4](https://doi.org/10.1145/3786583.3786857)</sup> |
| 执行模式 | 64.9% 的夹具方法在每个测试方法之前或之后运行；27.3% 在类级别运行一次<sup>[4](https://doi.org/10.1145/3786583.3786857)</sup> |
| 持续集成背景 | 83.4% 的开发者运行 CI/CD 流水线，这是采用最广泛的 DevOps 实践，因此测试装置通常在自动化流水线内执行<sup>[5](https://www.jetbrains.com/pages/state-of-cicd2026/)</sup> |

## 定义与范围

测试装置回答一个实际问题：既然被测代码可能并非一个完整程序，那么一批测试代码该如何执行？驱动程序是用受控输入调用被测单元的代码；测试替身则用来替代测试不打算实际调用的组件，例如数据库、网络服务或硬件设备。<sup>[1](https://glossary.istqb.org/en_US/term/test-harness?exact_matches_first=true&syllabus_id=23)</sup><sup> • </sup><sup>[2](https://api.glossary.istqb.org/storage/help/R0uz58NqLzUz48LVUuyGSF76NFj4LHQazSs0GlNS.pdf)</sup> 没有驱动程序，函数库就没有入口；没有测试替身，一个触及线上支付服务的测试所测量的就既包括代码，也包括该服务。

该术语的用法因社群而异。一些开发者狭义地用“测试装置”指运行器加脚手架，而把“测试框架”留给可复用的库；另一些人——正如一种广为流传的说法——则把测试运行器连同测试本身都视为测试装置。ISTQB 的定义刻意宽泛，涵盖执行套件所需的一切。<sup>[1](https://glossary.istqb.org/en_US/term/test-harness?exact_matches_first=true&syllabus_id=23)</sup>

## xUnit 模式

几乎所有主流测试装置都遵循一种可追溯至[肯特·贝克](https://www.edgepedia.org/zh/kent-beck)为 [Smalltalk](https://www.edgepedia.org/zh/smalltalk) 所写的 SUnit 框架的设计，该框架以《简单 Smalltalk 测试：使用模式》为题发表于 1994 年 10 月的《Smalltalk Report》。<sup>[3](https://www.cambridge.org/core/books/kent-becks-guide-to-better-smalltalk/simple-smalltalk-testing/0D2F14E0129D5EF29E85D796A5B845FC)</sup> SUnit 将测试组织为 TestCase 的子类，再组合为 TestSuite 实例；为每个测试用例提供各自的夹具，使一个用例中的错误不影响下一个；并提供诸如 `#should:` 之类的断言方法，当条件为假时中止测试并记录失败。<sup>[6](https://www.gnu.org/software/smalltalk/manual/html_node/SUnit.html)</sup><sup> • </sup><sup>[7](https://citeseerx.ist.psu.edu/document?doi=2f3f6892987e86f7559402215060d797387470ac&repid=rep1&type=pdf)</sup> Camp Smalltalk 的 SUnit 手册称原框架由四个类和十个方法组成。<sup>[8](https://sunit.sourceforge.net/manual.htm)</sup>

这一模式通过 xUnit 家族传播开来。Java 版本 JUnit 最初由埃里希·伽玛（Erich Gamma）与肯特·贝克编写，据称是 1997 年在从苏黎世飞往亚特兰大的航班上结对编程时完成的，其文档化特性包括断言、用于共享公共测试数据的测试夹具，以及测试运行器。<sup>[9](https://junit.org/junit4/faq.html)</sup><sup> • </sup><sup>[10](https://speakerdeck.com/asciamanna/beyond-unit-testing-the-real-value-of-tdd-agile5)</sup> JUnit 现已是第六代，由 JUnit Platform、Jupiter 和 Vintage 三个子项目组成，其中 Platform 定义了可供其他框架运行的 TestEngine API。<sup>[11](https://junit.org/)</sup><sup> • </sup><sup>[12](https://docs.junit.org/6.0.0/overview.html)</sup> 在 Python 中，pytest 自动发现测试模块与函数，提供用于管理测试资源的模块化夹具，并可直接运行现有的基于 unittest 的套件。<sup>[13](https://docs.pytest.org/en/stable/)</sup><sup> • </sup><sup>[14](https://docs.pytest.org/en/stable/unittest.html)</sup>

## 夹具：setup 与 teardown

夹具是测试运行时所处的固定状态。setup 方法在每个测试之前建立该状态；teardown 方法在之后将程序复位到先前的状态，这是一种避免测试之间产生副作用的手段，从而使隔离不依赖于执行顺序。<sup>[15](https://www.gregorykapfhammer.com/download/research/papers/key/Parry2022-paper.pdf)</sup>

一项针对开发者所编写测试的大规模研究（Hamster 研究，发表于 ICSE SEIP 2026）量化了夹具的实际使用情况。43.1% 的测试类包含至少一个 setup 方法，16.2% 包含至少一个 teardown 方法，无论是自定义还是继承而来。多数测试框架允许开发者通过注解或配置控制执行顺序：64.9% 的夹具方法在每个测试方法之前或之后运行，27.3% 在类级别运行一次。该研究还发现夹具被用于管理模拟对象，9.8% 的测试在 setup 方法中含有模拟代码，例如创建模拟的 HTTP 资源，使测试在隔离环境中运行。<sup>[4](https://doi.org/10.1145/3786583.3786857)</sup>

各框架的表达方式不尽相同。pytest 的夹具系统超越了 xUnit 风格的 setup 与 teardown：夹具是测试按名称请求的函数，可在类、模块、包或会话作用域内共享，可定义在按目录放置的 `conftest.py` 中而无需导入，夹具本身还可请求其他夹具，其清理通过终结机制处理。<sup>[16](https://docs.pytest.org/en/latest/reference/fixtures.html)</sup><sup> • </sup><sup>[17](https://docs.pytest.org/en/stable/contents.html)</sup> JUnit 的 unittest 风格对应物则提供 `setUp`、`tearDown`、`setUpClass` 和 `tearDownClass` 钩子，pytest 在运行 unittest 套件时予以支持。<sup>[14](https://docs.pytest.org/en/stable/unittest.html)</sup>

## 测试替身与保真度

由于测试装置经常必须替换依赖，替换方式的选择决定了测试能证明什么。谷歌的测试指南按保真度——即测试行为与生产行为的接近程度——对选项排序：条件允许时优先使用真实实现；否则使用伪件，即轻量级的可工作实现（如内存数据库），它保真度高，但需要自身经过测试以确认与真实行为一致；再否则使用模拟对象，其行为在测试中内联指定，不执行任何真实实现，保真度较低，但对于难以触发的路径（如超时错误条件）仍有用处。<sup>[18](https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html?hl=de_AT)</sup> 早前一期《谷歌测试小贴士》提出了互补的观点：当告诉模拟对象该如何表现时，所获得的唯一保证就是——只要模拟对象的行为与真实实现完全一致，代码就能正常工作；而这一保证会随代码变化而漂移。该文建议，在真实依赖过慢或经由网络通信时，使用封闭的本地服务器或伪件。<sup>[19](https://testing.googleblog.com/2013/05/testing-on-toilet-dont-overuse-mocks.html?hl=uk_UA&showComment=1373421337515)</sup>

Android 的测试文档使用同一套分类法：伪件具有适合测试但不适合生产的可工作实现；封闭测试则避免一切外部依赖，例如从互联网获取数据。<sup>[20](https://developer.android.com/training/testing/fundamentals/test-doubles)</sup>

## 封闭式测试装置与 CI 执行

现代测试装置大多在持续集成中运行。在 [JetBrains](https://www.edgepedia.org/zh/jetbrains) 的 2026 年调查中，83.4% 的开发者运行 CI/CD 流水线，高于容器化的 50% 和基础设施即代码的 39%，使流水线成为采用最广泛的 DevOps 实践；[GitHub Actions](https://www.edgepedia.org/zh/github-actions) 以 47% 在企业工具采用率中领先，GitLab CI 以 32% 次之，Jenkins 为 28%。<sup>[5](https://www.jetbrains.com/pages/state-of-cicd2026/)</sup> 因此，一个在开发者机器上与在流水线中表现不同的测试装置，会破坏整个信号。

封闭式测试通过让测试针对完全自包含、不依赖生产后端等外部依赖的环境运行来解决这一问题。<sup>[21](https://raw.githubusercontent.com/abseil/abseil.github.io/cd13b21daa6ec74155548241241693198c1b1264/resources/swe_at_google.2.pdf)</sup> 谷歌对封闭式服务器的设计指南要求：所有与其他服务器的连接须在运行时通过依赖注入注入；所需的静态文件须打包进服务器二进制文件；数据存储须可替换为伪件或内存实现——如此，整个被测系统可在单台机器上、无网络连接的情况下启动。<sup>[22](https://testing.googleblog.com/2012/10/hermetic-servers.html?hl=uk_UA&showComment=1502183041895)</sup> 其回报可能很大：谷歌的一个团队将预提交测试迁移到完全封闭的套件后，运行时间缩短至原来的十四分之一，且几乎没有偶发失败——此前非封闭的失败已变得司空见惯，某些日子有超过 50 项代码变更绕过并无视测试结果。<sup>[23](https://jinwoongkim.net/images/software-engineering-at-google-lessons-learned-from-programming-over-time-1nbsped-1492082791-9781492082798_compress.pdf)</sup> Fuchsia 将该方法推向平台层面：该操作系统上的所有测试默认都是封闭式的。<sup>[24](https://fuchsia.googlesource.com/fuchsia/%2B/e8f76dafcb34f4f77dadaa3a6c3174b8e69f8a08/docs/reference/testing/what-tests-to-write.md)</sup>

## 偶发失败：测试装置的质量问题

测试装置的可信度取决于其确定性。偶发失败测试（flaky test），即结果非确定性的测试，会降低测试的有效性与效率并延误发布；一项对 200 篇文章（109 篇学术文献与 91 篇灰色文献）的 2023 年多声部综述发现，来自测试顺序依赖与并发的偶发失败是研究最多的成因，而基于动态重跑的方案是主要的检测方法。<sup>[25](https://doi.org/10.1016/j.jss.2023.111837)</sup> 测试间共享状态是测试装置层面的直接成因：一个有记录的例子涉及两个使用同一 API 的测试，第一个测试在第二个执行前未重置夹具。<sup>[25](https://doi.org/10.1016/j.jss.2023.111837)</sup>

通过重跑来检测代价高昂。一项针对 Python 中偶发失败测试的研究估计，要以 95% 的置信度确认一个通过的测试用例并非结果不稳定的测试，平均需要 170 次重跑。<sup>[26](https://arxiv.org/abs/2101.09077)</sup> 近期的工业 CI 数据使问题更加突出：在所研究的项目中，未被检测到的偶发失败占失败流水线运行的 9.8% 至 16.3%，不同测试环境之间的偶发率最高可相差至 3 倍之比，而最具破坏性的案例对依赖现有检测机制的工具而言大多不可见。<sup>[27](https://xplorestaging.ieee.org/document/11673059/)</sup> 这些发现使上文的测试装置设计选择——夹具隔离、封闭环境与高保真替身——直接关系到流水线是否可靠。

## References

1. [test harness, ISTQB Glossary](https://glossary.istqb.org/en_US/term/test-harness?exact_matches_first=true&syllabus_id=23)
2. [Standard Glossary of Terms used in Software Testing, ISTQB](https://api.glossary.istqb.org/storage/help/R0uz58NqLzUz48LVUuyGSF76NFj4LHQazSs0GlNS.pdf)
3. [Kent Beck, "Simple Smalltalk Testing" (Smalltalk Report, October 1994), in Kent Beck's Guide to Better Smalltalk, Cambridge University Press](https://www.cambridge.org/core/books/kent-becks-guide-to-better-smalltalk/simple-smalltalk-testing/0D2F14E0129D5EF29E85D796A5B845FC)
4. [Hamster: A Large-Scale Study and Characterization of Developer-Written Tests, ICSE SEIP](https://doi.org/10.1145/3786583.3786857)
5. [The State of CI/CD in 2026, JetBrains TeamCity](https://www.jetbrains.com/pages/state-of-cicd2026/)
6. [GNU Smalltalk User's Guide: SUnit](https://www.gnu.org/software/smalltalk/manual/html_node/SUnit.html)
7. [SUnit chapter (Squeak/Portland State course text)](https://citeseerx.ist.psu.edu/document?doi=2f3f6892987e86f7559402215060d797387470ac&repid=rep1&type=pdf)
8. [Camp Smalltalk SUnit Manual](https://sunit.sourceforge.net/manual.htm)
9. [JUnit Frequently Asked Questions](https://junit.org/junit4/faq.html)
10. [Beyond Unit Testing: The Real Value of TDD, Anthony Sciamanna](https://speakerdeck.com/asciamanna/beyond-unit-testing-the-real-value-of-tdd-agile5)
11. [JUnit home page](https://junit.org/)
12. [JUnit 6.0.0 User Guide: Overview](https://docs.junit.org/6.0.0/overview.html)
13. [pytest documentation](https://docs.pytest.org/en/stable/)
14. [How to use unittest-based tests with pytest](https://docs.pytest.org/en/stable/unittest.html)
15. [A Survey of Flaky Tests (Parry et al., 2022)](https://www.gregorykapfhammer.com/download/research/papers/key/Parry2022-paper.pdf)
16. [Fixtures reference, pytest documentation](https://docs.pytest.org/en/latest/reference/fixtures.html)
17. [Full pytest documentation](https://docs.pytest.org/en/stable/contents.html)
18. [Increase Test Fidelity By Avoiding Mocks, Google Testing Blog](https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html?hl=de_AT)
19. [Testing on the Toilet: Don't Overuse Mocks, Google Testing Blog](https://testing.googleblog.com/2013/05/testing-on-toilet-dont-overuse-mocks.html?hl=uk_UA&showComment=1373421337515)
20. [Use test doubles in Android, Android Developers](https://developer.android.com/training/testing/fundamentals/test-doubles)
21. [Software Engineering at Google (chapter on hermetic testing)](https://raw.githubusercontent.com/abseil/abseil.github.io/cd13b21daa6ec74155548241241693198c1b1264/resources/swe_at_google.2.pdf)
22. [Hermetic Servers, Google Testing Blog](https://testing.googleblog.com/2012/10/hermetic-servers.html?hl=uk_UA&showComment=1502183041895)
23. [Software Engineering at Google: Lessons Learned from Programming Over Time (hermetic presubmit case)](https://jinwoongkim.net/images/software-engineering-at-google-lessons-learned-from-programming-over-time-1nbsped-1492082791-9781492082798_compress.pdf)
24. [Fuchsia: What Tests to Write](https://fuchsia.googlesource.com/fuchsia/%2B/e8f76dafcb34f4f77dadaa3a6c3174b8e69f8a08/docs/reference/testing/what-tests-to-write.md)
25. [Test flakiness' causes, detection, impact and responses: A multivocal review, Journal of Systems and Software 206 (2023)](https://doi.org/10.1016/j.jss.2023.111837)
26. [An Empirical Study of Flaky Tests in Python, arXiv:2101.09077](https://arxiv.org/abs/2101.09077)
27. [An Empirical Study of Detected and Undetected Flaky Test Failures in Real-World CI Pipelines, IEEE Transactions on Software Engineering](https://xplorestaging.ieee.org/document/11673059/)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software testing and quality › Test infrastructure and tooling

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/test-harness

English original: https://www.edgepedia.org/test-harness
