开发者

How to set DateTime as ValuesAttribute to unit test?

开发者 https://www.devze.com 2023-01-28 12:32 出处:网络
I want to do somethi开发者_C百科ng like this [Test] public void Test([Values(new DateTime(2010, 12, 01),

I want to do somethi开发者_C百科ng 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


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);
    }
}


Just pass the dates as string constants and parse inside your test. A bit annoying but it's just a test so don't worry too much.

[TestCase("1/1/2010")]
public void mytest(string dateInputAsString)
{
  DateTime dateInput= DateTime.Parse(dateInputAsString);
  ...
}


Define a custom attribute that accepts six parameters and then use it as

[Values(2010, 12, 1, 2010, 12, 3)]

and then construct the necessary instances of DateTime accordingly.

Or you could do

[Values("12/01/2010", "12/03/2010")]

as that might be a little more readable and maintainable.

As the error message says, attribute values can not be non-constant (they are embedded in the metadata of the assembly). Contrary to appearances, new DateTime(2010, 12, 1) is not a constant expression.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号