Currently I'm writing a unit test for a component that does datetime specific validation. I have created IDateTimeProvider
interface, that serves as a DateTime.UtcNow
wraper and business objects use interface rather than DateTime
directly. It seems that DateTime is a bit overloaded and should be split into a value and a thing that gets that value from the OS. I wonder if there is a particular reason not to have a IDateTimeProvider
(IClock
) interface in .NET?
DateTime. Today is DateTime. Now with time set to zero.
The Now property returns a DateTime value that represents the current date and time on the local computer.
DateTime. Now is over 10X SLOWER than DateTime.
Explanation: In the above example, first of all, we find tomorrow's date by adding today's date with the timespan of 1. Here, we get today's date using the DateTime. Now method.
Simply put: because large parts of the BCL weren't designed for testability.
The same is true for random number generation, in terms of "core" functionality - and a lot of the HTTP-related classes are much worse to fake out :( At least in this case it's reasonably easy to introduce your own clock interface.
On the plus side, when Noda Time is ready for production use, it will not only provide a better date/time API than the BCL - it'll provide a more test-friendly one :)
We consistently use a DateTimeProvider wrapper class which we can override in a test context if necessary...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With