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

Mic*_*ech 24 c# nunit unit-testing

我想做这样的事情

[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);
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了关于参数的以下错误

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

有什么建议?


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

Ced*_*icB 25

作为膨胀单元测试的替代方法,您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*dyM 15

只需将日期作为字符串常量传递并在测试中解析.有点烦人,但这只是一个测试,所以不要太担心.

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

  • (小心你的语言环境) (5认同)

jas*_*son 5

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

[Values(2010, 12, 1, 2010, 12, 3)]
Run Code Online (Sandbox Code Playgroud)

然后DateTime相应地构造必要的实例。

或者你可以这样做

[Values("12/01/2010", "12/03/2010")]
Run Code Online (Sandbox Code Playgroud)

因为这可能更具可读性和可维护性。

正如错误消息所述,属性值不能是非常量的(它们嵌入在程序集的元数据中)。与表面现象相反,new DateTime(2010, 12, 1)它不是一个常量表达式。