After System.Random Isolation I now want to isolate System.DateTime. The information in the struct is not very interesting, but the Now property is. That is a static property. Does that require a different approach? Hardly.
IDateTime
First I’ll define the interface for the DateTime struct. There will be nothing inside because static operations/properties cannot be defined in an interface.
IDateTimeFactory
My factory interface will contain the property, but not as a static. Read on to see why.
DateTime
The DateTime class will implement the IDateTime interface, which is empty, but for completeness I’ve added it.
In the Reset method the Factory property is set to the SystemDateTimeFactory defined below, for now all you need to know it results in using the System.DateTime.
The Factory property is static and is used to create an instance saved in Implementation in the constructors of the DateTime object. Again this is only for completeness, no actual use of this. But the Factory is used for every static call on my DateTime object.
What this means is that the static property Now calls the method on the Factory.
public static System.DateTime Now { get { return Factory.Now; } }
Getting clearer now?
SystemDateTimeWrapper
Again, the interface is empty, so nothing to do here.
SystemDateTimeFactory
Here the default implementation that points to System.DateTime.Now is programmed. Implement the IDateTimeFactory interface and redirect the Now property.
public System.DateTime Now { get { return System.DateTime.Now; } }
Sample
Replace the factory used with your own implementation to influence the current date. Maybe to check if someone is old enough to drive a car?
// ARRANGE // our fake datetime factory that returns our fake Now information var fakeFactory = MockRepository.GenerateStub<IDateTimeFactory>(); var now = new DateTime(2013, 11, 1); // november 1st fakeRandomFactory.Expect(x => x.Now).Return(now); // use our fake setup in the execution to know what day it is // going to be every time SystemIoslation.DateTime.Factory = fakeFactory;
Take away
As shown above isolating statics can be handled with the same approach, only use the factory interface.