To write tests for classes with strong, hard coded, dependencies is always hard. One very common dependency is the dependency on the DateTime.Now-property. For example we have a “HelloWorld”-class (I’ve never written a Hello World-example actually so I just had to) that should greet us differently depending on the time of day.
This code is very hard to test because we would have to either run the test on different times of the day to see that it returns the correct result or we would have to make the test set the system time in order to test the output. What we would like to do is to stub, mock or in some other way fake out the DateTime.Now property but we can’t since it’s a static. To break this dependency we’ll have to add some layer of indirection between the code and the static property. This is where dependency injection comes into play. As the code is right now, there’s no way for someone looking from the outside to see that this class has a dependency on the DateTime.Now-property. Using dependency injection and more specifically constructor injection makes this very clear.
First of all, let’s create our “layer of indirection”, the SystemTime-delegate which is a simple delegate type that returns the current time of the system.:
Now we make this dependency explicit by having our class take an instance of a SytemTime-delegate in it’s constructor and also we’ll use this delegate to access the system time rather than the DateTime.Now-property:
Now it’s very easy to create tests that verify the output at different times by passing SystemTime-delegates that provide different times of the day:
And of course for production code you’d just pass in a delegate that access the DateTime.Now-property, preferably using an IoC-container, but it could certainly be done manually.