Skip to content

Instantly share code, notes, and snippets.

@gabrieljoelc
Created January 22, 2014 18:07
Show Gist options
  • Save gabrieljoelc/8564008 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/8564008 to your computer and use it in GitHub Desktop.
Testable DateTime.Now using IDisposable pattern http://www.limilabs.com/blog/testing-datetime-now
[Test]
public void CreateName_AddsCurrentTimeAtEnd()
{
using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))
{
string name = new ReportNameService().CreateName(...);
Assert.AreEqual("name 2010-12-31 23:59:00", name);
}
}
public class Clock : IDisposable
{
private static DateTime? _nowForTest;
public static DateTime Now
{
get { return _nowForTest ?? DateTime.Now; }
}
public static IDisposable NowIs(DateTime dateTime)
{
_nowForTest = dateTime;
return new Clock();
}
public void Dispose()
{
_nowForTest = null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment