Bending DateTime in .NET to Test Your Code Better
Mocking DateTime in .NET is painful, here’s a way to make it hurt less.
Okay I’ll dial down the hyperbole, over my years (read I’m feeling old) as an engineer I have run into a problem where my code has contained a DateTime.Now
or DateTime.UtcNow
. When I write a test, I can't validate the actual time because milliseconds have passed between the code running and validating.
It's not a huge problem but annoying as I like to validate everything to make sure I'm not accidentally manipulating those values somewhere else.
There is an easy solution to this, and before I detail the solution that I used, I need to call out the inspirations for this. Thanks to Andrew Harcourt, Andrew Wickens and Jared Wilton for giving me that extra push.
The TL;DR; is that you can consume my SimpleDateTimeProvider NuGet package to help you solve this. The implementation of the code for this lies below.
The Solution
I have created a DateTimeProvider
consisting of an interface, and two implementations of the interface. One implementation returns the System values and the other returns Mocked values that are preset by the user.