如何提高具有大量参数的TestCase的可读性

时间:2016-04-02 08:19:56

标签: c# unit-testing nunit

这是一个主要是概念性的问题。我有一些类表示从(自定义)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));
}

你可以看到它是一个非常简单的测试。我提供了IEnumerable string TestCase和选择区域的算法,但是很难看到 - 乍一看 - Array ( [1] => Array ( [num_copy] => 1 [dwg_rev] => B [dwg_id] => 1 ) [2] => Array ( [num_copy] => 1 [dwg_rev] => B [dwg_id] => 2 ) ) Array ( [1] => Array ( [client_id] => 1 ) ) 参数在哪里。我在想 - 是否有一个更清洁的"这样做的方式? 旁注:我的测试就像这个一样简单,但必须提供更多的参数......

1 个答案:

答案 0 :(得分:1)

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

[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,引用fixture类中的静态数组......

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(..

这些是我可以看到的最佳选项,而不会更改测试的参数,如果它是我的代码,那就是我实际会做的。

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

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

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

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

相关问题