c#unit test - 重载方法测试的命名约定

时间:2011-04-14 15:55:00

标签: c# unit-testing naming-conventions overloading

我在c#中有一些简单的扩展方法我正在编写单元测试。其中一种扩展方法是重载的,所以我很难为单元测试提出合理的命名约定。

示例重载方法:

public static class StringExtensions
{
    public static List<string> ToList(this string value, char delimiter)
    {
        return ToList(value, new[] { delimiter });
    }

    public static List<string> ToList(this string value, char[] delimiterSet) { .. }
}

如果我想写两个单元测试,每个方法一个,你会如何命名测试?通常我会简单地使用:

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTest

但是有两个同名的方法,我很难找到一个好的约定..

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTest

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTestOverload

太可怕了。

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTestWithChar

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTestWithCharArray

基于参数类型更好,但仍然非常糟糕。

有些人可能会建议编写一个针对两个重载的测试方法,但理想情况下我希望与单元测试和方法保持1:1的关系,即使过载当前是链接的。我不希望在测试中做出任何超载被链接和传递的假设。

你会怎么做?

3 个答案:

答案 0 :(得分:14)

Roy Osherove在他的书“单位测试的艺术”中建议根据您尝试测试的行为命名约定,而不一定在生产方法和测试方法之间进行一对一的映射。所以,作为一个简单的例子,假设我有一个像这样的Stack类:

public class Stack
{
    public void Push(int value);
    public int Pop();
    public bool IsEmpty();
}

编写测试的一种方法是使用三种测试方法:

[TestMethod]
public void PushTest

[TestMethod]
public void PopTest

[TestMethod]
public void IsEmptyTest

但是,有一种更好的测试方法可以指定Stack类的行为。接下来的想法是,您可以在类行为和测试方法之间进行一对一的映射。因此,一种行为是空堆栈上的IsEmpty返回true。另一个是推送一个元素使堆栈不为空。然后,我将根据这些简单的英语句子以Arrange/Act/Assert格式编写测试,以下列格式指定这些行为:

MethodName_StateOfTheObject_ExpectedResult

所以对于上面提到的行为:

[TestMethod]
IsEmpty_OnEmptyStack_ReturnsTrue

[TestMethod]
Push_OnEmptyStack_MakesStackNotEmpty

我建议您考虑一下您尝试在上述方法中测试的行为,然后将这些行为映射到测试中。例如:

[TestMethod]
ToList_OnEmptyString_ReturnsEmptyList

[TestMethod]
ToList_OnStringWithDelimiters_ReturnsListWithTokensSeparatedByDelemiter

[TestMethod]
ToList_OnStringWithoutDelimiters_ReturnsListWithOneString

更多信息here

答案 1 :(得分:4)

我倾向于选择后者,但不是基于传入的参数,而是基于测试的实际功能。

所以不是:

  • TestFunctionWithListOfNumbers
  • TestFunctionWithListOfStrings

但也许:

  • TestFunctionWithStudentIDs
  • TestFunctionWithStudentNames

答案 2 :(得分:2)

我倾向于以更多Given,When,Then方式编写测试名称。这使得测试名称变得冗长,但它告诉我正在测试的功能是什么。所以在你的情况下,我会进行测试

[TestMethod]
public void GivenSingleCharDelimeter_ToList_Returnsxxx()
[TestMethod]
public void GivenCharArrayDelimeter_ToList_Returnsxxx()