C# – How to set DateTime as ValuesAttribute to unit test

cnunitunit testing

I want to do something like this

[Test]
public void Test([Values(new DateTime(2010, 12, 01), 
                         new DateTime(2010, 12, 03))] DateTime from, 
                 [Values(new DateTime(2010, 12, 02),
                         new DateTime(2010, 12, 04))] DateTime to)
{
    IList<MyObject> result = MyMethod(from, to);
    Assert.AreEqual(1, result.Count);
}

But I get the following error regarding parameters

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

Any suggestions?


UPDATE: nice article about Parameterized tests in NUnit 2.5
http://www.pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html

Best Answer

An alternative to bloating up your unit test, you can offload the creation of the TestCaseData using the TestCaseSource attribute.

TestCaseSource attribute lets you define a method in a class that will be invoked by NUnit and the data created in the method will be passed into your test case.

This feature is available in NUnit 2.5 and you can learn more here...

[TestFixture]
public class DateValuesTest
{
    [TestCaseSource(typeof(DateValuesTest), "DateValuesData")]
    public bool MonthIsDecember(DateTime date)
    {
        var month = date.Month;
        if (month == 12)
            return true;
        else
            return false;
    }

    private static IEnumerable DateValuesData()
    {
        yield return new TestCaseData(new DateTime(2010, 12, 5)).Returns(true);
        yield return new TestCaseData(new DateTime(2010, 12, 1)).Returns(true);
        yield return new TestCaseData(new DateTime(2010, 01, 01)).Returns(false);
        yield return new TestCaseData(new DateTime(2010, 11, 01)).Returns(false);
    }
}