如何将 DateTime 设置为 ValuesAttribute 进行单元测试? [英] How to set DateTime as ValuesAttribute to unit test?

查看:40
本文介绍了如何将 DateTime 设置为 ValuesAttribute 进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情

[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

有什么建议吗?

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

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

推荐答案

另一种增加单元测试的方法是,您可以使用 TestCaseSource 属性卸载 TestCaseData 的创建工作.

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

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

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.

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

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

这篇关于如何将 DateTime 设置为 ValuesAttribute 进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆