System.DateTime isolation

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.



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.



My factory interface will contain the property, but not as a static. Read on to see why.



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?



Again, the interface is empty, so nothing to do here.



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; }


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?

// 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.

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Test and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.