Search code examples
c#unit-testingtddsolid-principlessingle-responsibility-principle

How to write similar test cases without breaking the Single Responsibility Principle?


I have created one unit test for different inputs, to make sure the outputs are correct.

[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
    }

Because the cases are very similar, I put them in one test method. Is that behavior okay or does it break the Single Responsibility Principle? If it breaks SRP, what is a better solution?


Solution

  • I decided to answer my own question

    So as I am not using any third party framework or library for test, instead I am using the default MSTest. I ended up doing this

        [TestMethod]
        public void CountInversionTestCase1()
        {
            CountInversionTest(new int[] { 4, 3, 2, 1 }, 6);
        }
        [TestMethod]
        public void CountInversionTestCase2()
        {
            CountInversionTest(new int[] { 1, 3, 5, 2, 4, 6 }, 3);
        }
        [TestMethod]
        public void CountInversionTestCase3()
        {
            CountInversionTest(new int[] { 5, 6, 2, 3, 1, 4, 7 }, 10);
        }
    
        public void CountInversionTest(int[] sourceArray, int expectedInversionCount)
        {
            #region Act
            Sorter sorter = new Sorter();
            long actualInversionCount = sorter.CountInversion(sourceArray);
            #endregion
    
            #region Assert
            Assert.AreEqual(expectedInversionCount, actualInversionCount);
            #endregion
        }
    

    Which is not the best solution out there, but it satisfies the requirements and doesn't use any third party library. I hope it helps anyone out there.