如何将DateTime设置为ValuesAttribute进行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 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

作为膨胀unit testing的替代方法,您可以使用TestCaseSource属性卸载TestCaseData的创建。

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

此function在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); } } 

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

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

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

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

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

或者你可以做到

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

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

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