nUnit test cases with dates

nUnit has a great feature of running multiple similar test cases via data-driven approach:

[TestCase("", "")]
[TestCase("q", "q")]
[TestCase("xyz", "zyx")]
public void TestStringReverse(string s, string expectedResult)
{
    var result = Reverse(s);
    Assert.AreEqual(expectedResult, result);
}

However, that does not work with dates, since DateTime is not a primitive type and cannot be used in an attribute.

[TestCase(new DateTime(...), new DateTime(...), false)] // Does not work
public void TestIntervalIsGood(DateTime from, DateTime to, bool isGood)
{
    ...
}

The solution is to supply test data in runtime, using [ValueSource] attribute. This is more code, but it works.

        // warning: not tested
        public class Interval
        {
            public DateTime From;
            public DateTime To;
        }

        public class TestCase
        {
            public int Id;
            public DateTime From;
            public DateTime To;
            public bool IsGood;

            // We need this override, so test cases are shown well in nUnit. Otherwise they all look like MyTestClass+TestCase
            // We could show actual dates, but it is kind of long, so I opted for a numeric ID
            public override string ToString()
            {
                return "TestCase " + Id;
            }
        }

        private static TestCase T(int id, DateTime from, DateTime to, bool isGood)
        {
            return new TestCase { Id = id, From = from, To = to, IsGood = isGood };
        }

        private static readonly DateTime Before = ...;
        private static readonly DateTime Inside = ...;
        private static readonly DateTime After = ...;

        private static readonly TestCase[] TestCases =
        {
            T(1, Before, Before, false),
            T(2, Before, Inside, true),
            T(3, Before, After, true)
        };

        public void TestIntervalIsGood([ValueSource(nameof(TestCases))] TestCase testCase)
        {
            bool isGood = IsIntervalGood(testCase.From, testCase.To);
            Assert.AreEqual(testCase.IsGood, isGood);
        }

Leave a Reply

Your email address will not be published. Required fields are marked *