Skip to content

Instantly share code, notes, and snippets.

@ryanohs
Created July 31, 2014 04:44
Show Gist options
  • Save ryanohs/c0e64a16f1cb5fd76095 to your computer and use it in GitHub Desktop.
Save ryanohs/c0e64a16f1cb5fd76095 to your computer and use it in GitHub Desktop.
public static class SystemTime
{
private static readonly ThreadLocal<Func<DateTime>> _Now = new ThreadLocal<Func<DateTime>>(() => () => DateTime.Now);
public static DateTime Now
{
get { return _Now.Value(); }
}
public static ResetSystemTime Set(DateTime executionTime)
{
_Now.Value = () => executionTime;
return new ResetSystemTime();
}
public static void Reset()
{
_Now.Value = () => DateTime.Now;
}
public class ResetSystemTime : IDisposable
{
public void Dispose()
{
Reset();
}
}
}
public class Bar
{
public DateTime LastModified { get; set; }
public void UpdateTime()
{
LastModified = SystemTime.Now;
}
}
[TestFixture]
public class Tests : AssertionHelper
{
[Test]
public void SetsLastModifiedTimeToCurrentTime()
{
var foo = new Bar();
var executionTime = new DateTime(2014, 1, 1);
using (SystemTime.Set(executionTime))
{
foo.UpdateTime();
}
Expect(foo.LastModified, Is.EqualTo(executionTime));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment