一般
所有测试都遵循相同的标准。
清楚每个测试状态是什么。
明确预期的行为。
例子
1) MethodName_StateUnderTest_ExpectedBehavior
Public void Sum_NegativeNumberAs1stParam_ExceptionThrown()
Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown ()
Public void Sum_simpleValues_Calculated ()
来源:单元测试的命名标准
2)用下划线分隔每个单词
Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown()
Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown ()
Public void Sum_Simple_Values_Calculated ()
其他
用Test结束方法名
用类名开始方法名
我倾向于使用MethodName_DoesWhat_WhenTheseConditions的约定,例如:
Sum_ThrowsException_WhenNegativeNumberAs1stParam
然而,我所看到的是使测试名称遵循的单元测试结构
安排
行为
断言
它也遵循BDD / Gherkin语法:
鉴于
当
然后
这将是命名测试的方式:UnderTheseTestConditions_WhenIDoThis_ThenIGetThis
对于你的例子:
WhenNegativeNumberAs1stParam_Sum_ThrowsAnException
然而,我更喜欢把测试的方法名放在前面,因为这样测试就可以按字母顺序排列,或者在VisStudio的成员下拉框中按字母顺序排列,并且一个方法的所有测试都被分组在一起。
在任何情况下,我喜欢用下划线分隔测试名称的主要部分,而不是每个单词,因为我认为这样更容易阅读和理解测试的要点。
换句话说,我更喜欢:Sum_ThrowsException_WhenNegativeNumberAs1stParam,而不是sum_throw_exception_when_negative_number_as_1st_param。
我倾向于使用MethodName_DoesWhat_WhenTheseConditions的约定,例如:
Sum_ThrowsException_WhenNegativeNumberAs1stParam
然而,我所看到的是使测试名称遵循的单元测试结构
安排
行为
断言
它也遵循BDD / Gherkin语法:
鉴于
当
然后
这将是命名测试的方式:UnderTheseTestConditions_WhenIDoThis_ThenIGetThis
对于你的例子:
WhenNegativeNumberAs1stParam_Sum_ThrowsAnException
然而,我更喜欢把测试的方法名放在前面,因为这样测试就可以按字母顺序排列,或者在VisStudio的成员下拉框中按字母顺序排列,并且一个方法的所有测试都被分组在一起。
在任何情况下,我喜欢用下划线分隔测试名称的主要部分,而不是每个单词,因为我认为这样更容易阅读和理解测试的要点。
换句话说,我更喜欢:Sum_ThrowsException_WhenNegativeNumberAs1stParam,而不是sum_throw_exception_when_negative_number_as_1st_param。
我确实像其他方法一样命名我的测试方法,使用“pascal套管”,没有任何下划线或分隔符。我省略了方法的后缀Test,因为它没有增加任何值。属性TestMethod表示该方法是一个测试方法。
[TestMethod]
public void CanCountAllItems() {
// Test the total count of items in collection.
}
由于每个Test类应该只测试另一个类,所以我在方法名中去掉了类名。包含测试方法的类的名称与被测试类的名称相同,带有后缀“Tests”。
[TestClass]
public class SuperCollectionTests(){
// Any test methods that test the class SuperCollection
}
对于测试异常或不可能的操作的方法,i在测试方法前加上单词Cannot。
[TestMethod]
[ExpectedException(typeOf(ArgumentException))]
public void CannotAddSameObjectAgain() {
// Cannot add the same object again to the collection.
}
我的命名惯例是基于Bryan Cook的文章“TDD技巧:测试命名惯例和指南”。我发现这篇文章很有帮助。