c# - 如何在不违反单一职责原则的情况下编写类似的测试用例?

标签 c# unit-testing tdd solid-principles single-responsibility-principle

我为不同的输入创建了一个单元测试,以确保输出正确。

[TestMethod]
    public void CountInversionTest()
    {
        #region Arrange
        int[] sourceArray = {4, 3, 2, 1};
        int correctInversionCount = 6;
        int[] sourceArray2 = { 1, 3, 5, 2, 4, 6};
        int correctInversionCount2 = 3;
        int[] sourceArray3 = { 5, 6, 2, 3, 1, 4, 7 };
        int correctInversionCount3 = 10;
        #endregion

        #region Act
        Sorter sorter = new Sorter();
        int inversionCount = sorter.CountInversion(sourceArray);
        int inversionCount2 = sorter.CountInversion(sourceArray2);
        int inversionCount3 = sorter.CountInversion(sourceArray3);
        #endregion

        #region Assert
        Assert.AreEqual(correctInversionCount, inversionCount);
        Assert.AreEqual(correctInversionCount2, inversionCount2);
        Assert.AreEqual(correctInversionCount3, inversionCount3);
        #endregion
    }

因为案例非常相似,所以我把它们放在一个测试方法中。这种行为是正确的还是违反了单一职责原则?如果它破坏了 SRP,什么是更好的解决方案?

最佳答案

使用适当的单元测试框架,如 xUnit.net , 你可以写一个 Parameterized Test相反:

[Theory]
[InlineData(new[] { 4, 3, 2, 1 }, 6)]
[InlineData(new[] { 1, 3, 5, 2, 4, 6 }, 3)]
[InlineData(new[] { 5, 6, 2, 3, 1, 4, 7 }, 10)]
public void ParameterizedCountInversionTest(int[] input, int expected)
{
    Sorter sut = new Sorter();
    var actual = sut.CountInversion(input);
    Assert.Equal(expected, actual);
}

这将运行三个测试,而不是一个,让您更好地了解哪个特定测试用例失败(如果有任何失败)。

这样测试也更具可读性。

NUnit也有这个功能,但 MSTest 没有(我上次看的时候)。

关于c# - 如何在不违反单一职责原则的情况下编写类似的测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876652/

相关文章:

c# - XNA 的 TiledLib 在加载时抛出 ArgumentException

swift - for 循环内的代码覆盖率不正确

visual-studio - 在 Visual Studio 中,有没有办法自动生成唯一的方法名称?

java - Gradle "test"任务没有在应该失败的地方失败

c# - Rhino 模拟,VerifyAllExpectations

c# - 当文件上传超过 ASP.NET MVC 中允许的大小时显示自定义错误页面

c# - WPF 组合框 : Align selected value and/or drop down items

c# - 标签文本未更新

java - 单个测试类的模拟机

c# - 在最小起订量中重置模拟验证?