如何将 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 表达式 或数组创建表达式
什么建议吗?
更新:关于 NUnit 2.5 中参数化测试的好文章
http://www .pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html
I want to do something like this
[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);
}
But I get the following error regarding parameters
An attribute argument must be a
constant expression, typeof expression
or array creation expression of an
Any suggestions?
UPDATE: nice article about Parameterized tests in NUnit 2.5
http://www.pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为膨胀单元测试的替代方法,您可以使用 TestCaseSource 属性来卸载 TestCaseData 的创建。
TestCaseSource 属性允许您在类中定义将由 NUnit 调用的方法,并且在该方法中创建的数据将传递到您的测试用例中。
NUnit 2.5 中提供了此功能,您可以在此处了解更多信息...
An alternative to bloating up your unit test, you can offload the creation of the TestCaseData using the TestCaseSource attribute.
TestCaseSource attribute lets you define a method in a class that will be invoked by NUnit and the data created in the method will be passed into your test case.
This feature is available in NUnit 2.5 and you can learn more here...
只需将日期作为字符串常量传递并在测试中进行解析即可。
有点烦人,但这只是一个测试,所以不用太担心。
Just pass the dates as string constants and parse inside your test.
A bit annoying but it's just a test so don't worry too much.
定义一个接受六个参数的自定义属性,然后将其用作
并相应地构造必要的
DateTime
实例。或者你可以
这样做,因为这可能更具可读性和可维护性。
正如错误消息所述,属性值不能是非常量的(它们嵌入在程序集的元数据中)。与表面上相反,
new DateTime(2010, 12, 1)
不是常量表达式。Define a custom attribute that accepts six parameters and then use it as
and then construct the necessary instances of
DateTime
accordingly.Or you could do
as that might be a little more readable and maintainable.
As the error message says, attribute values can not be non-constant (they are embedded in the metadata of the assembly). Contrary to appearances,
new DateTime(2010, 12, 1)
is not a constant expression.