2010-12-03 64 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