wip-6.0
zeroChapter 6 Styles of unit testing
第 6 章 单元测试的风格
This chapter covers
本章涵盖:
- Comparing styles of unit testing
比较单元测试的不同风格。 - The relationship between functional and hexagonal architectures
函数式架构与六边形架构之间的关系。 - Transitioning to output-based testing
向基于输出的测试转变。
Chapter 4 introduced the four attributes of a good unit test: protection against regressions, resistance to refactoring, fast feedback, and maintainability. These attributes form a frame of reference that you can use to analyze specific tests and unit testing approaches. We analyzed one such approach in chapter 5: the use of mocks.
第 4 章介绍了优秀单元测试的四个属性:防止回归、抗重构能力、快速反馈和可维护性。这些属性构成了一个参照框架,你可以用它分析具体测试和单元测试方法。第 5 章我们分析了其中一种方法:mock 的使用。
In this chapter, I apply the same frame of reference to the topic of unit testing styles. There are three such styles: output-based, state-based, and communication-based testing. Among the three, the output-based style produces tests of the highest quality, state-based testing is the second-best choice, and communication-based testing should be used only occasionally.
在本章中,我会把同一套参照框架应用到单元测试风格这一主题上。单元测试有三种风格:基于输出、基于状态和基于通信的测试。在这三者中,基于输出的风格能产出质量最高的测试,基于状态的测试是第二好的选择,而基于通信的测试只应偶尔使用。
Unfortunately, you can’t use the output-based testing style everywhere. It’s only applicable to code written in a purely functional way. But don’t worry; there are techniques that can help you transform more of your tests into the output-based style. For that, you’ll need to use functional programming principles to restructure the underlying code toward a functional architecture.
遗憾的是,你不能在所有地方都使用基于输出的测试风格。它只适用于以纯函数方式编写的代码。但不用担心,有一些技术可以帮助你把更多测试转变为基于输出的风格。为此,你需要使用函数式编程原则,把底层代码重构为函数式架构。
Note that this chapter doesn’t provide a deep dive into the topic of functional programming. Still, by the end of this chapter, I hope you’ll have an intuitive understanding of how functional programming relates to output-based testing. You’ll also learn how to write more of your tests using the output-based style, as well as the limitations of functional programming and functional architecture.
请注意,本章不会深入探讨函数式编程这一主题。不过,到本章结束时,我希望你能直观理解函数式编程与基于输出的测试之间的关系。你也会学到如何用基于输出的风格编写更多测试,以及函数式编程和函数式架构的局限。