We all love unit tests (do we?). Yes we do (repeat 100 times). And we all love mocking for making life easier, but sometimes we just want to write some simple unit tests that don't require any mocking at all, because the code you are testing is easy to test without having to resort to all those mocking tricks
But what if you need to test code that relies on the date or some elapsed time? Let's say you wrote a simple caching class that automatically removes items from the cache when a certain amount of time has passed since the last access. It's tempting to slap some Thread.Sleep() calls in there to trigger expiration of cache items, but that will slow down your unit test, and most importantly, it's not accurate. What if you want to test some edge cases? Like, what happens when you access an item at the exact timeout period?
A few years ago I worked with a brilliant Java architect who simply said: "just mock the time!". What he meant was that I should create a fake DateTime class which behaves like the real DateTime class with one important difference: YOU control the time, not the system clock.
How is that done?
Simply create an interface with a single getter property of type DateTime:
public interface ITimeProvider
{
DateTime Now { get; }
}
Then you create 2 classes that implement this interface: one that returns the real time, and one that can be used to control a "fake" time:
public class RealTimeProvider : ITimeProvider
{
public DateTime Now { get { return DateTime.Now; } }
}
public class MockTimeProvider : ITimeProvider
{
private DateTime _time;
public DateTime Now { get { return _time; } set { _time = value; } }
}
Of course the class(es) you want to test should be aware of this. For example, our cache class could look like this:
public class Cache
{
private ITimeProvider _time = new RealTimeProvider();
public ITimeProvider TimeProvider { get { return _time; } set { _time = value; } }
// ... the rest of the class implementation
}
In our class implementation, all calls to DateTime.Now should be replaced by TimeProvider.Now.
And now the fun part, faking the time in our unit tests:
[Test]
public void TestCacheTimeout()
{
ITimeProvider time = new MockTimeProvider();
Cache cache = new Cache();
cache.TimeProvider = time; // Tell our cache class to use our fake time
cache.Add("A" , 1); // add an item to the cache
Assert.IsTrue(cache.Contains("A")); // check if it's added
time.Now += TimeSpan.FromHours(1); // let one hour go by...
Assert.IsFalse(cache.Contains("A")); // check if it was automatically removed
}
That's pretty cool and simple, isn't it? Wouldn't it be nice if we could do the same in real life? 
Next week I'll talk a little about unit testing multithreaded concurrency issues...

•