How can "today's date" be varied for unit testing purposes?
Posted
by ck
on Stack Overflow
See other posts from Stack Overflow
or by ck
Published on 2010-03-20T04:36:01Z
Indexed on
2010/03/20
4:41 UTC
Read the original article
Hit count: 321
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 defaultsbaselineDate
toDateTime.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 toDateTime.Today
. When testing, derive aDateCalculatorForTesting
fromDateCalculator
and setbaslineDate
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.
© Stack Overflow or respective owner