3 ms·
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 I
by PJDK 10y ago
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.
- hirsin 10y agoSorry, what's the connection between August and the UK? Based in the US, but I can't think of a specific month I'd want my tests to run in.
- limeyx 10y agoNot sure for sure but August is probably the least rainy/nasty month in England
- PJDK 10y agoIt's summer time - during the winter the UK runs on UTC, so if you've forgot to do a timezone conversion you don't spot it until the clocks change in spring. Having tests use the time in summer make this easier to spot.