2010-12-03 71 views
23

我想要做这样的事情如何将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); 
} 

,但我得到有关参数

的属性参数必须是 常量表达式以下错误的typeof的

的表达 或数组创建表达式

有什么建议吗?


UPDATE:有关参数测试好的文章在NUnit的2.5
http://www.pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html

回答

25

另一种扩展单元测试的方法是使用TestCaseSource属性卸载TestCaseData的创建。

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

此功能可在NUnit的2.5,你可以学到更多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); 
    } 
} 
3

定义接受六个参数的自定义属性,然后用它作为

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

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

或者你可以做

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

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

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

15

只是传递日期为字符串常量和解析您的测试中。 有点烦人,但它只是一个测试,所以不要太担心。

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

(小心你的语言环境) – AndyM 2012-02-08 03:49:37