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

KP.*_*KP. 9 c# unit-testing overloading naming-conventions

我在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) { .. }
}
Run Code Online (Sandbox Code Playgroud)

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

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTest
Run Code Online (Sandbox Code Playgroud)

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

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

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTestOverload
Run Code Online (Sandbox Code Playgroud)

太可怕了.

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

[TestMethod, TestCategory("Single Method Tests")]
public void ToListTestWithCharArray
Run Code Online (Sandbox Code Playgroud)

基于参数类型更好,但仍然非常可怕.

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

你会怎么做?

Bri*_*ler 14

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

public class Stack
{
    public void Push(int value);
    public int Pop();
    public bool IsEmpty();
}
Run Code Online (Sandbox Code Playgroud)

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

[TestMethod]
public void PushTest

[TestMethod]
public void PopTest

[TestMethod]
public void IsEmptyTest
Run Code Online (Sandbox Code Playgroud)

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

MethodName_StateOfTheObject_ExpectedResult
Run Code Online (Sandbox Code Playgroud)

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

[TestMethod]
IsEmpty_OnEmptyStack_ReturnsTrue

[TestMethod]
Push_OnEmptyStack_MakesStackNotEmpty
Run Code Online (Sandbox Code Playgroud)

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

[TestMethod]
ToList_OnEmptyString_ReturnsEmptyList

[TestMethod]
ToList_OnStringWithDelimiters_ReturnsListWithTokensSeparatedByDelemiter

[TestMethod]
ToList_OnStringWithoutDelimiters_ReturnsListWithOneString
Run Code Online (Sandbox Code Playgroud)

更多信息在这里