NUnit parameterized tests with datetime

nunitunit testing

Is it not possible with NUnit to go the following?

[TestCase(new DateTime(2010,7,8), true)]
public void My Test(DateTime startdate, bool expectedResult)
{
    ...
}

I really want to put a datetime in there, but it doesn't seem to like it. The error is:

An attribute argument must be a constant expression, typeof expression
or array creation expression of an attribute parameter type

Some documentation I read seems to suggest you should be able to, but I can't find any examples.

Best Answer

You can specify the date as a constant string in the TestCase attribute and then specify the type as DateTime in the method signature.

NUnit will automatically do a DateTime.Parse() on the string passed in.

Example:

[TestCase("01/20/2012")]
[TestCase("2012-1-20")] // Same case as above in ISO 8601 format
public void TestDate(DateTime dt)
{
    Assert.That(dt, Is.EqualTo(new DateTime(2012, 01, 20)));
}
Related Topic