A DateTime.Now representation that can be alterd during testing.
If you have a pice of code that is dependant of the current time you usually use the DateTime.Now property. But when writing tests to that piece of code you are unable to stub or mock DateTime.Now, since it's a static call.
Therefore I created this:
public static class SystemTime
{
private static Func<DateTime> Time = () => DateTime.Now;
public static DateTime Now
{
get { return Time(); }
}
/// <summary>
/// Resets SystemTime.Now to return DateTime.Now
/// </summary>
public static void Reset()
{
Time = () => DateTime.Now;
}
/// <summary>
/// Fix the time to fixedTime. All calls to SystemTime.Now will return fixedTime
/// </summary>
/// <param name="value"></param>
public static void FixTo(DateTime fixedTime)
{
Time = () => fixedTime;
}
/// <summary>
/// Fix the time to time. All calls to SystemTime.Now will return time offsetted with the time since this method was last called
/// </summary>
/// <param name="value"></param>
public static void SetTo(DateTime time)
{
var offset = time - DateTime.Now;
Time = () => DateTime.Now + offset;
}
}
This makes it possible to write tests that look like this:
public void MyUnitTest()
{
SystemTime.FixTo(new DateTime(2011, 2, 15, 18, 0, 0));
var anObject = CallToTimeDependantMethod1();
SystemTime.FixTo(new DateTime(2011, 2, 16, 20, 0, 0));
var result = CallToTimeDependantMethod2(anObject);
Assert.Equal(new Timespan(1, 2, 0, 0), result.Duration);
}
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


1.04k
0




Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'