unit-testingnunit

NUnit parameterized tests with datetime


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.


Solution

  • I'd probably use something like the ValueSource attribute to do this:

    public class TestData
    {
        public DateTime StartDate{ get; set; }
        public bool ExpectedResult{ get; set; }
    }
    
    private static TestData[] _testData = new[]{
        new TestData(){StartDate= new DateTime(2010, 7, 8), ExpectedResult= true}};
    
    [Test]
    public void TestMethod([ValueSource("_testData")]TestData testData)
    {
    }
    

    This will run the TestMethod for each entry in the _testData collection.