Search code examples
c#delegatesnunitparameterized-unit-test

Is there a way to pass delegates to a NUnit TestCase or TestFixture?


Basically I want to be able to plug-in methods to a TestCase or TestFixture in NUnit to vary the behavior. In essence I want to do this:

[TestFixture]
public class MethodTests
{
    public delegate void SimpleDelegate();

    public static void A()
    {
        // Do something meaningful
    }

    public static void B()
    {
        // Do something meaningful
    }

    public static void C()
    {
        // Do something meaningful
    }

    [TestCase(A,B,C)]
    [TestCase(C,A,B)]
    [TestCase(C,B,A)]
    public void Test(SimpleDelegate action1, SimpleDelegate action2, SimpleDelegate action3 )
    {
        action1();
        action2();
        action3();
    }
}

The errors I get back for [TestCase(A,B,C)] are

  • Error 6 Argument 1: cannot convert from 'method group' to 'object'
  • Error 7 Argument 2: cannot convert from 'method group' to 'object'
  • Error 8 Argument 3: cannot convert from 'method group' to 'object'

Do you know if there is any way to get this or something like it to work?


Solution

  • This is where the TestCaseSourceAttribute comes to the rescue.

    First, define an object array containing your list of test cases. Next, invoke the test cases by referencing to the object array as the Test's [TestCaseSource]. This should build and run as you intended.

    private static readonly object[] TestCases =
    {
        new SimpleDelegate[] { A, B, C },
        new SimpleDelegate[] { C, A, B },
        new SimpleDelegate[] { C, B, A }
    };
    
    [Test, TestCaseSource("TestCases")]
    public void Test(SimpleDelegate action1, SimpleDelegate action2, 
                     SimpleDelegate action3)
    {
        action1();
        action2();
        action3();
    }
    

    If you need a more complex argument list, you could for example use Tuple instead of SimpleDelegate[] to create strongly typed argument lists.