Home > Software engineering >  Is it a bad idea to use DateTime.MinValue / MaxValue in unit tests?
Is it a bad idea to use DateTime.MinValue / MaxValue in unit tests?

Time:07-21

I'm writing some unit tests, which use some objects with date properties that I need to set.

Instead of defining my own hardcoded dates, I've been using DateTime.MinValue and MaxValue.

I've heard unit tests should be deterministic, but the C# docs say that MinValue/MaxValue are static readonly fields and not constants. Would this make my tests nondeterministic? Also I'm wondering if I should just define my own hardcoded dates instead for the tests.

CodePudding user response:

The values aren't compile-time constants, because they can't be - but they'll never change. Your unit tests are fine in terms of being deterministic.

That said, there are oddities about DateTime.MinValue and DateTime.MaxValue, in terms of how they'll respond to arithmetic operations (e.g. you can't subtract a day from DateTime.MinValue).

That means in at least some cases it's useful to have:

  • A test case for a "normal" date
  • A test case for DateTime.MinValue
  • A test case for DateTime.MaxValue

... just in case your code ought to handle extreme values but doesn't for some reason. That said, it really depends on the code you're testing.

  • Related