如何将DateTime设置为ValuesAttribute以进行单元测试?

27

我想做类似这样的事情

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

但是我遇到了有关参数的以下错误:

属性参数必须是常量表达式、typeof表达式或数组创建表达式

有什么建议吗?


更新:在NUnit 2.5中关于参数化测试的一个不错的文章
http://www.pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html

3个回答

28

除了让你的单元测试变得臃肿外,你还可以使用TestCaseSource属性来卸载创建TestCaseData的工作。

TestCaseSource属性允许您在类中定义一个方法,该方法将由NUnit调用,并且在方法中创建的数据将传递到您的测试用例中。

此功能在NUnit 2.5中可用,您可以在此处了解更多信息...

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

20

只需将日期作为字符串常量传递并在测试内解析即可。 有点烦人,但这只是一个测试,不必太担心。

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

7
请提供需要翻译的英文文本。 - AndyM
快速而简单,但我喜欢它。 - openshac

5

定义一个自定义属性,接受六个参数,然后将其用作

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

然后相应地构建所需的DateTime实例。

或者您可以这样做

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

正如错误信息所说,属性值不能是非常量的(它们被嵌入到程序集的元数据中)。与外表不同,new DateTime(2010, 12, 1) 不是一个常量表达式。因此,为了使代码更易读且易于维护,建议使用其他方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接