Search code examples
c#unit-testingnunit

TestCase() in C#- problem with DateTime argument


Hey I wrote a test in C# which as argument takes only one DateTime argument. What I would like to do is to add [TestCase(new DateTime(2022, 1, 31))] above my test but when I try to do that I get an error that "An attribute must be a constant expression, typeof expression or array creation expression of an attribute parameter type". What can I do?


Solution

  • Any use of new in the argument list to TestCaseAttribute will get you the same error. Because of the restrictions that C# imposes, NUnit provides TestCaseSourceAttribute.

    However, TestCaseSourceAttribute involves more typing and in this case, you can provide a string as the argument. Note that the argument to the test method should still be typed as a DateTime even though you are providing a string. As noted in one of the comments, NUnit is smart enough to convert it.

    [TestCase("2022/1/31")]
    public void MyTestMethod(DateTime dt)
    {
        ...
    }