c# 单元测试 - 重载方法测试的命名约定

标签 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 的关系,即使重载当前是链接的。我不想在测试中做出任何假设,即重载是链接和传递的。

你会如何处理这个问题?

最佳答案

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

关于c# 单元测试 - 重载方法测试的命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5666013/

相关文章:

php - 如何更好地解耦我的数据层并限制我的单元测试范围?

c# - 单元测试不会运行 : process is terminated due to StackOverflowException

ruby - 使用 rspec 断言用户数组中的所有 user.name 都以前缀开头的更好方法?

c - 多用途结构方法的命名约定

r - 制作好的列名 R

c# - 在 C# 中使用 .Add 的二维数组

c# - 一种抛出异常并记录它的方法

c# - 使用命令在加载页面 (Xamarin.Forms) 时填充 ListView

c# - 如果我没有为 CSharpCodeProvider 指定 CompilerVersion 会发生什么,为什么大多数示例都指定了它?

C# .net - 接口(interface)/实现方案中的 Dll 命名约定