原文:7 Popular Unit Test Naming Conventions
本文介绍了一系列在单元测试命名中可以遵循的命名策略,本文仅作参考,不作详细叙述。如果希望了解更多细节,请参考下面列出的文章。
- Naming Standards for Unit Tests
- Naming Unit Tests Responsibly
- What are some popular naming conventions for unit tests?
- Unit Tests Naming Best Practices
- GivenWhenThen Technique
基于上述文章,以下是7种被大多数开发者使用的单元测试命名约定:
MethodName_StateUnderTest_ExpectedBehavior:
反对这种策略的人认为,如果重构代码时方法名发生改变,那么单元测试命名也需要相应改变,否则以后将会难以理解。以下是一些示例:
- isAdult_AgeLessThan18_False
- withdrawMoney_InvalidAccount_ExceptionThrown
- admitStudent_MissingMandatoryFields_FailToAdmit
MethodName_ExpectedBehavior_StateUnderTest:
对上面的策略稍加调整,一部分开发者也推荐使用这种命名方法。这种方法也有缺点,如果方法名发生改变,以后它将变得难以理解。以下是在第一个示例中的
test[Feature being tested]:
- testIsNotAnAdultIfAgeLessThan18
- testFailToWithdrawMoneyIfAccountIsInvalid
- testStudentIsNotAdmittedIfMandatoryFieldsAreMissing
Feature to be tested:
- IsNotAnAdultIfAgeLessThan18
- FailToWithdrawMoneyIfAccountIsInvalid
- StudentIsNotAdmittedIfMandatoryFieldsAreMissing
Should_ExpectedBehavior_When_StateUnderTest:
- Should_ThrowException_When_AgeLessThan18
- Should_FailToWithdrawMoney_ForInvalidAccount
- Should_FailToAdmit_IfMandatoryFieldsAreMissing
When_StateUnderTest_Expect_ExpectedBehavior:
- When_AgeLessThan18_Expect_isAdultAsFalse
- When_InvalidAccount_Expect_WithdrawMoneyToFail
- When_MandatoryFieldsAreMissing_Expect_StudentAdmissionToFail
Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior:
- Given_UserIsAuthenticated_When_InvalidAccountNumberIsUsedToWithdrawMoney_Then_TransactionsWillFail