A good solution is to abstract the external dependencies in order to be able to drown them out during the test. To virtualize time, I often use something like this:
public interface ITimeService { DateTime Now { get; } void Sleep(TimeSpan timeSpan); }
In your case, you do not need the Sleep part, since you will depend only on the current time, and, of course, you need to change your code to use the ITimeService supplied from the outside when the current time is required.
Usually you should use this implementation:
public class TimeService : ITimeService { public DateTime Now { get { return DateTime.Now; } public void Sleep(TimeSpan timeSpan) { Thread.Sleep(timeSpan); } }
For testing purposes, you can use this stub:
public class TimeServiceStub : ITimeService { public TimeServiceStub(DateTime startTime) { Now = startTime; } public DateTime Now { get; private set; } public void Sleep(TimeSpan timeSpan) { Now += timeSpan; } }
source share