How to set DateTime as ValuesAttribute on unit test?

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

The attribute argument must be a constant expression, a typeof expression, or an array creation expression

Any suggestions?




UPDATE: a good article on parameterized tests in NUnit 2.5
http://www.pgs-soft.com/new-features-in-nunit-2-5-part-1-parameterized-tests.html

+23
c # unit-testing nunit
Dec 03 '10 at 10:35
source share
3 answers

An alternative to bloating your unit test, you can offload the creation of TestCaseData using the TestCaseSource attribute.

The TestCaseSource attribute allows you to define a method in the class that will be called by NUnit, and the data created in the method will be passed to your test case.

This feature is available in NUnit 2.5, and you can learn more 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); } } 
+25
Dec 05 '10 at 4:08
source share

Just pass dates as string constants and parse inside your test. A bit annoying, but it's just a test, so don't worry too much.

 [TestCase("1/1/2010")] public void mytest(string dateInputAsString) { DateTime dateInput= DateTime.Parse(dateInputAsString); ... } 
+14
Apr 04 2018-11-11T00:
source share

Define a custom attribute that takes six parameters, and then use it as

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

and then create the necessary DateTime instances accordingly.

Or you could do

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

as it may be a little more readable and maintainable.

As the error message says, attribute values ​​cannot be inconsistent (they are embedded in assembly metadata). Contrary to appearance, new DateTime(2010, 12, 1) not a constant expression.

+3
Dec 03 '10 at 15:40
source share



All Articles