Search code examples
c#nunittestcasenunit-2.5.9testcaseattribute

Improving test syntax for immensely many test cases


I've got me a test method and a bunch of test cases as follows.

[TestCase(1, 2)]
[TestCase(3, 4)]
[TestCase(5, 6)]
public void Smack(int a, int b) { ... }

I've hidden the bunch of cases in a region but it doesn't feel right. I've tried with the other attributes listed at the official web page but didn't really got that to work (a bit confused on the proper way to approach it). Also, a colleague hinted that using the permutations and such can cause issues.

Is the below the best way to phrase a bunch of test cases or is there anything smoother and more pro?

#region Bunch
[TestCase(1, 2)]
[TestCase(3, 4)]
[TestCase(5, 6)]
#endregion
public void Smack(int a, int b) { ... }

Solution

  • You might try using a TestCaseSource:

    [TestCaseSource("SmackTestCases")]
    public void Smack(int a, int b) { ... }
    
    static object[] SmackTestCases =
    {
        new object[] { 1, 2 },
        new object[] { 3, 4 },
        new object[] { 5, 6 } 
    };
    

    You could also implement this in a separate class, like this:

    [TestFixture]
    public class MyTests
    {
        [Test]
        [TestCaseSource(typeof(SmackTestDataProvider), "TestCases")]
        public void Smack(int a, int b) { ... }
    }
    
    public class SmackTestDataProvider
    {
        public static IEnumerable TestCases
        {
            get
            {
                yield return new TestCaseData( 1, 2 );
                yield return new TestCaseData( 3, 4 );
                yield return new TestCaseData( 5, 6 );
            }
        }  
    }