Skip to content

Instantly share code, notes, and snippets.

@aligneddev
Last active March 15, 2021 16:16
Show Gist options
  • Save aligneddev/2f3d1fbba4bdf453d19b30ab32fd30c4 to your computer and use it in GitHub Desktop.
Save aligneddev/2f3d1fbba4bdf453d19b30ab32fd30c4 to your computer and use it in GitHub Desktop.
SystemTime wrapper around DateTime for a unit testing hook
// another option? https://blog.burgyn.online/2019/12/06/date-time-provider
using System;
namespace Shared.Core.Implementations
{
/// <summary>
/// Testable alternative to DateTime.Now or DateTimeOffset.Now
/// </summary>
public static class SystemTime
{
private static DateTime? _dateTimeHolder = null;
/// <summary>
/// Gets the current local DateTimeOffset
/// </summary>
public static DateTime Now => _dateTimeHolder ?? DateTime.Now;
/// <summary>
/// Allow overriding the time for testing
/// </summary>
/// <param name="fakeDateTime"></param>
public static void SetNow(DateTime fakeDateTime)
{
_dateTimeHolder = fakeDateTime;
}
public static void ResetNow()
{
_dateTimeHolder = null;
}
private static DateTimeOffset? _offsetHolder = null;
/// <summary>
/// Gets the current local DateTimeOffset
/// </summary>
public static DateTimeOffset NowOffset => _offsetHolder ?? DateTimeOffset.Now;
/// <summary>
/// Allow overriding the time for testing
/// </summary>
/// <param name="fakeDateTimeOffset"></param>
public static void SetNowOffset(DateTimeOffset fakeDateTimeOffset)
{
_offsetHolder = fakeDateTimeOffset;
}
public static void ResetOffsetNow()
{
_offsetHolder = null;
}
}
}
using System;
namespace SystemTime
{
public class SystemTime
{
protected static Func<DateTime> localNow = () => DateTime.Now;
public static DateTime Now
{
get => localNow();
protected set { localNow = () => value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace SystemTime.Testing
{
public class TestingSystemTime : SystemTime
{
public static DateTime StartForTest()
{
Now = DateTime.Now;
return Now;
}
public static DateTime Reset()
{
localNow = () => DateTime.Now;
return localNow();
}
public static DateTime AddMinutes(int mins)
{
Now = Now.AddMinutes(mins);
return Now;
}
public static DateTime AddHours(int hours)
{
Now = Now.AddHours(hours);
return Now;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment