Unit testing a method that depends on the current DateTime: Part 3 of 3

This post it the conclusion to a series. Make sure you alse read Part 1 and Part 2.

It’s time to concentrate on the implementation of our Outlet class. We will add a new private property where we set the time zones of each company.

private readonly string[] timezones =
    "Pacific Standard Time",
    "Central Standard Time",

This information would be fetched from a data store in practice, and you would do well to use an interface as well so it can be mocked. But I will leave this part for you as an exercise.

The code for fetching the current date and time is now as follows.

public string GetLocalDateTime(long id)
    var tz = TimeZoneInfo.FindSystemTimeZoneById(timezones[id]);
    var currentDate = dateTimeWrapper.Now();
    var offset = tz.GetUtcOffset(currentDate);
    var outletDate = currentDate.AddMinutes(offset.TotalMinutes);

    return outletDate.ToString("M/d/yyyy HH:mm");

So this method calculates the selected company’s timezone first through FindSystemTimeZoneById, and then reads the date and time from the wrapper we created in part 2. We continue by getting the timezone offset for this particular date by means of GetUtcOffset. This step is required because the offset is different between winter and summer due to daylight saving. The final step is to add this offset to the date (note also that it is in minutes because some time zones vay by half-hour steps) and return it as a string.

We did the change with confidence, and can now look at the test results:

All the tests are passing

We have now observed how code that interacts with the hosting system should be written. Whilst using the operating system’s resources is essential in a software program, having indirect access to those resources ensures that your code will be easier to test independently of any environment that it will run on.

Now that you know the basic concept, I have to reveal that there is a library that already does this. This popular library is NodaTime, which the authors describe as a better date and time API for .NET. NodaTime exposes everything through the ICock interface and even provides a mocking solution in the form of FakeClock.

Buy me a coffee Buy me a coffee


Add your comments