【翻译】7种流行的单元测试命名约定

原文:7 Popular Unit Test Naming Conventions

本文介绍了一系列在单元测试命名中可以遵循的命名策略,本文仅作参考,不作详细叙述。如果希望了解更多细节,请参考下面列出的文章。

基于上述文章,以下是7种被大多数开发者使用的单元测试命名约定:

  1. MethodName_StateUnderTest_ExpectedBehavior:

    反对这种策略的人认为,如果重构代码时方法名发生改变,那么单元测试命名也需要相应改变,否则以后将会难以理解。以下是一些示例:

    • isAdult_AgeLessThan18_False
    • withdrawMoney_InvalidAccount_ExceptionThrown
    • admitStudent_MissingMandatoryFields_FailToAdmit
  2. MethodName_ExpectedBehavior_StateUnderTest:

    对上面的策略稍加调整,一部分开发者也推荐使用这种命名方法。这种方法也有缺点,如果方法名发生改变,以后它将变得难以理解。以下是在第一个示例中的

  3. test[Feature being tested]:

    • testIsNotAnAdultIfAgeLessThan18
    • testFailToWithdrawMoneyIfAccountIsInvalid
    • testStudentIsNotAdmittedIfMandatoryFieldsAreMissing
  4. Feature to be tested:

    • IsNotAnAdultIfAgeLessThan18
    • FailToWithdrawMoneyIfAccountIsInvalid
    • StudentIsNotAdmittedIfMandatoryFieldsAreMissing
  5. Should_ExpectedBehavior_When_StateUnderTest:

    • Should_ThrowException_When_AgeLessThan18
    • Should_FailToWithdrawMoney_ForInvalidAccount
    • Should_FailToAdmit_IfMandatoryFieldsAreMissing
  6. When_StateUnderTest_Expect_ExpectedBehavior:

    • When_AgeLessThan18_Expect_isAdultAsFalse
    • When_InvalidAccount_Expect_WithdrawMoneyToFail
    • When_MandatoryFieldsAreMissing_Expect_StudentAdmissionToFail
  7. Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior:

    • Given_UserIsAuthenticated_When_InvalidAccountNumberIsUsedToWithdrawMoney_Then_TransactionsWillFail
原文地址:https://www.cnblogs.com/ilcc/p/4111316.html