Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit parameterized tests with datetime

Is it not possible with NUnit to go the following?

[TestCase(new DateTime(2010,7,8), true)] public void My Test(DateTime startdate, bool expectedResult) {     ... } 

I really want to put a datetime in there, but it doesn't seem to like it. The error is:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Some documentation I read seems to suggest you should be able to, but I can't find any examples.

like image 897
AnonyMouse Avatar asked Aug 18 '11 21:08

AnonyMouse


People also ask

How do I use Testcasesource in NUnit?

TestCaseSourceAttribute is used on a parameterized test method to identify the source from which the required arguments will be provided. The attribute additionally identifies the method as a test method. The data is kept separate from the test itself and may be used by multiple test methods.

How can you make a NUnit test case Datadriven?

The first way to create data driven tests is by using the [TestCase] attribute that NUnit provides. You can add multiple [TestCase] attributes for a single test method, and specify the combinations of input and expected output parameters that the test method should take.

How do you write multiple test cases in NUnit?

Make more copies of the attribute if you want multiple cases. The data type of the values provided to the TestCase attribute should match with that of the arguments used in the actual test case.

How do I write a unit test case in NUnit?

Creating the first testSave this file and execute the dotnet test command to build the tests and the class library and run the tests. The NUnit test runner contains the program entry point to run your tests. dotnet test starts the test runner using the unit test project you've created.


1 Answers

You can specify the date as a constant string in the TestCase attribute and then specify the type as DateTime in the method signature.

NUnit will automatically do a DateTime.Parse() on the string passed in.

Example:

[TestCase("01/20/2012")] [TestCase("2012-1-20")] // Same case as above in ISO 8601 format public void TestDate(DateTime dt) {     Assert.That(dt, Is.EqualTo(new DateTime(2012, 01, 20))); } 
like image 87
RonnBlack Avatar answered Oct 08 '22 19:10

RonnBlack