如何提高具有大量参数的测试用例的可读性

How to improve readability of a TestCase with lots of parameters

这主要是一个概念性问题。我有一些 class 表示从(自定义)TextArea 控件中删除文本的算法。我想测试一下 - 当然是算法 ;)。我担心我的测试方法缺乏可读性:

[TestCase(new[] { "some text asdf" }, 5, 0, 9, 0, "some  asdf", new int[0])]
[TestCase(new[] { "some text", "", "totally unimportant texttext that stays" }, 0, 0, 24, 2, "text that stays", new[] { 0, 1, 2 })]
public void ShouldRemoveSelectedText(string[] lines, int colStart, int lineStart, int colEnd, int lineEnd, string notRemovedText, int[] expectedRemovedLines) {
    var newLines = algorithm.RemoveLines(lines, new TextPositionsPair {
        StartPosition = new TextPosition(column: colStart, line: lineStart),
        EndPosition = new TextPosition(column: colEnd, line: lineEnd)
    });

    Assert.That(newLines.LinesToChange.First().Value, Is.EqualTo(notRemovedText));
    CollectionAssert.AreEqual(expectedRemovedLines, newLines.LinesToRemove.OrderBy(key => key));
}

如您所见,这是一个非常简单的测试。我为算法提供 stringIEnumerable 和选择区域,但很难看出 - 乍一看 - 哪个 TestCase 参数去哪里。我想知道 - 是否有 "cleaner" 方法可以做到这一点? 旁注:我有像这个一样简单的测试,但必须提供更多参数...

一种简单的方法是在每个案例中使用更多行...

[TestCase(new [] { "some text asdf" },
          5, 0, 9, 0,
          "some  asdf",
          new int[0])]
[TestCase(new [] { "some text", "", "totally unimportant texttext that stays" },
          0, 0, 24, 2,
          "text that stays",
          new [] {0, 1, 2})]
public void ShouldRemoveSelectedText(...

或者,您可以使用 TestCaseSource,引用夹具中的静态数组 class...

TestCaseData[] MySource = {
    new TestCaseData(new [] { "some text asdf" },
                     5, 0, 9, 0,
                     "some  asdf",
                     new int[0]),
    new TestCaseData(new [] { "some text", "", "totally unimportant texttext that stays" },
                     0, 0, 24, 2
                     "text that stays",
                     new [] { 0, 1, 2})};

[TestCaseSource("MySource")]
public void ShouldRemoveSelectedText(..

这些是我在不更改测试参数的情况下看到的最佳选项,如果这是我的代码,我实际上会这样做。

我会创建一个对象来封装文本缓冲区和另一个用于选择的对象。我在这里展示 classes,但它们可能是结构...

class TextBuffer
{
    public string[] Lines;
    public Selection Selection;
    ...
}

class Selection
{
    public int FromLine;
    public int FromCol;
    public int ToLine;
    public int ToCol;
    ...
}

然后我会根据这些测试原语重写测试,使其更易于阅读。