wip-3.7
zeroSummary
总结
All unit tests should follow the AAA pattern: arrange, act, assert. If a test has multiple arrange, act, or assert sections, that’s a sign that the test verifies multiple units of behavior at once. If this test is meant to be a unit test, split it into several tests—one per each action.
所有单元测试都应该遵循 AAA 模式:安排、执行、断言。如果一个测试中有多个 arrange、act 或 assert 区段,这说明该测试一次验证了多个行为单元。如果这个测试本意是单元测试,就把它拆成多个测试——每个动作对应一个测试。More than one line in the act section is a sign of a problem with the SUT’s API. It requires the client to remember to always perform these actions together, which can potentially lead to inconsistencies. Such inconsistencies are called invariant violations. The act of protecting your code against potential invariant violations is called encapsulation.
act 区段超过一行,通常说明 SUT 的 API 存在问题。它要求客户端记住始终把这些动作一起执行,这可能导致不一致。这类不一致称为不变量违背。保护代码免受潜在不变量违背影响的行为称为封装。Distinguish the SUT in tests by naming it
sut. Differentiate the three test sections either by putting Arrange, Act, and Assert comments before them or by introducing empty lines between these sections.
在测试中通过把 SUT 命名为sut来突出它。可以通过在三个测试区段前添加 Arrange、Act、Assert 注释,或在这些区段之间插入空行,来区分这三个部分。Reuse test fixture initialization code by introducing factory methods, not by putting this initialization code to the constructor. Such reuse helps maintain a high degree of decoupling between tests and also provides better readability.
复用测试夹具初始化代码时,应引入工厂方法,而不是把初始化代码放进构造函数。这样的复用有助于在测试之间保持高度解耦,同时也提供更好的可读性。Don’t use a rigid test naming policy. Name each test as if you were describing the scenario in it to a non-programmer who is familiar with the problem domain. Separate words in the test name by underscores, and don’t include the name of the method under test in the test name.
不要使用僵硬的测试命名策略。命名每个测试时,要像是在向一个熟悉问题领域的非程序员描述其中的场景。测试名中的单词用下划线分隔,并且不要在测试名中包含被测方法的名称。Parameterized tests help reduce the amount of code needed for similar tests. The drawback is that the test names become less readable as you make them more generic.
参数化测试有助于减少相似测试所需的代码量。缺点是,当你把测试变得更通用时,测试名称会变得不那么可读。Assertion libraries help you further improve test readability by restructuring the word order in assertions so that they read like plain English.
断言库通过重构断言中的词序,让断言读起来像普通英语,从而进一步提升测试可读性。