How can "today's date" be varied for unit testing purposes?
- by ck
I use VS2008 targetting .NET 2.0 Framework, and, just in case, no I can't change this :)
I have a DateCalculator class. Its method GetNextExpirationDate attempts to determine the next expiration, internally using DateTime.Today as a baseline date.
As I was writing unit tests, I realized that I wanted to test GetNextExpirationDate for different 'today' dates.
What's the best way to do this? Here are some alternatives I've considered:
Expose a property/overloaded method with argument baselineDate and only use it from the unit test. In actual client code, disregard the property/overloaded method in favour of the method that defaults baselineDate to DateTime.Today. I'm reluctant to do this as it makes the public interface of the DateCalculator class awkward.
Create a protected field called baselineDate that is internally set to DateTime.Today. When testing, derive a DateCalculatorForTesting from DateCalculator and set baslineDate via the constructor. It keeps the public interface clean, but still isn't great - baselineDate was made protected and a derived class is required, both solely for testing.
Use extension methods. I tried this after adding the ExtensionAttribute, then realized it wouldn't work because extension methods can't access private/protected variables. I initially thought this was really quite an elegant solution. :(
I'd be interested in hearing what others think.