Lazy DatetimeProvider trick
I was reviewing code and I noticed an interesting idea. A method called DatetimeProvider.ForceNow which would return an IDisposable object. In a using block, you can force a specific time.
Is it a good idea? Don't know yet, but I decided to talk about it The use of such method is almost exclusively about unit and integration tests. The IDisposable pattern assumes that you want to make sure you control the block where the time is set. But how is that different from just setting the time? The block is the unit test, after all. If you want multiple values, you just set those.
I always love me a little IDisposable used as a block control mechanism, but I feel here it is misused. The biggest issue I see is that it introduces testing behavior in the DatetimeProvider. The normal way - and the one I think it's best - is that you inject an IDatetimeProvider and during tests you mock it.
However, one must consider the advantages of such a mechanism, as well. You don't need to inject anything if you have a static DatetimeProvider. And then the only way to change its behavior for testing purposes is to add the methods to do that in it. It's lazy, but it works.
Conclusion: I prefer the injection mechanism. It's general - doesn't apply only to time providers - it's clean, it promotes separation (and declaration) of concerns. In fact I would go so far as to call this ForceNow idea an antipattern.
Comments
Be the first to post a comment