【问题标题】:How to set DateTime as ValuesAttribute to unit test?如何将 DateTime 设置为 ValuesAttribute 以进行单元测试?
【发布时间】:2010-12-03 10:35:58
【问题描述】:

我想做这样的事情

[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 表达式 或数组的创建表达式

有什么建议吗?


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

【问题讨论】:

    标签: c# unit-testing nunit


    【解决方案1】:

    您可以使用 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • (注意你的语言环境)
      • 又快又脏,但我喜欢。
      【解决方案3】:

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

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

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

      或者你可以这样做

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

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

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

      【讨论】:

        猜你喜欢
        • 2013-09-11
        • 1970-01-01
        • 2015-09-03
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 2014-11-25
        • 1970-01-01
        • 2013-11-18
        相关资源
        最近更新 更多