Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set DateTime as ValuesAttribute to unit test?

Tags:

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

like image 477
MicTech Avatar asked Dec 03 '10 10:12

MicTech


People also ask

Can you mock DateTime now?

The wrapper implementation will access DateTime and in the tests you'll be able to mock the wrapper class. Use Typemock Isolator, it can fake DateTime. Now and won't require you to change the code under test. Use Moles, it can also fake DateTime.

Can I use loop in unit test?

Yes you can have loops in unit test, but with caution. As mentioned by Alex York, loops are acceptable if you test one thing; i.e. one expectation. If you use loops, then I recommend that you must do two things: As mentioned above, test for a non-empty iteration set.

How do I run a MSTest unit test?

To run MSTest unit tests, specify the full path to the MSTest executable (mstest.exe) in the Unit Testing Options dialog. To call this dialog directly from the editor, right-click somewhere in the editor and then click Options.


1 Answers

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...

[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);     } } 
like image 181
CedricB Avatar answered Sep 21 '22 11:09

CedricB