Our solution in c# with dependency injection looks like this.
Any class that needs to know the time has the following object injected in.
public interface IDateTime
{
DateTime UtcNow { get; }
DateTime Today { get; }
}
StructureMap is configured to pass in the following concrete implementation.
public class DefaultDateTime : IDateTime
{
public DateTime UtcNow
{
get { return DateTime.UtcNow; }
}
public DateTime Today
{
get { return DateTime.Today; }
}
}
Obviously you can expand this to include local time, we haven't in order to prevent accidental use of Now when you mean UtcNow.
All of our tests inherit from a base test that does various set up stuff (clear down the db in integration tests for example). One of the things it does is swap out DefaultDateTime with this...
public class TestDateTime : IDateTime
{
private DateTime _testDateTime;
public TestDateTime(DateTime testDateTime)
{
_testDateTime = testDateTime;
}
public void ChangeTimeTo(DateTime testDateTime)
{
_testDateTime = testDateTime;
}
public DateTime UtcNow
{
get { return _testDateTime.ToUniversalTime(); }
public DateTime Today
{
get { return _testDateTime.Date; }
}
}
Where _testDateTime is set to be sometime in August (always a good idea if you're developing in the UK!). This has the added advantage of making test runs deterministic (at least in this respect) even if you're not doing a time related test.