Unit testing time sensitive code can be tricky because unit tests should be 100% repeatable, and the same each time. The system clock will never be the same each time the test is run, so it’s difficult to assert time-dependant values.
Sometimes you have code that depends on the time moving on, so a static clock with a fixed time value is of no use (say for example generating some unique key values based partly on the current time).
What I want is at the top of a test to “start the clock” once, where it will then continue to act like a clock from then on. I solved this problem as many people do – by providing a layer of abstraction from the system clock:
The default implementation is as follows:
This allows classes such as this (I use Castle Windsor to wire the dependencies up when not in unit tests):
It’s a bit more heavy-handed than Ayende’s solution, but the treacle is in the implementation of the test datetime provider:
The big win here is that you can set the “start time” of the test. As long as you assert the current values of the datetime provider etc against the results of the method calls, you should be okay. I realise there could be inconsistencies depending on how long the tests take to run etc, but a lot of that can be mitigated by being careful obtaining the time only once at the top of a method and referring back to it each time as in my example.