chobo2
chobo2

Reputation: 85795

How to unit test TimeZones?

I am wondering how to you test TimeZone logic? For me my timezone stuff is used to filter data from the database(what of course in unit tests gets mocked up and not tested).

But I would like to test the logic around it to see if I give certain times in that it would be converted right.

I am not sure how to do this though.

Upvotes: 2

Views: 4766

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038990

public class ClassToTest
{
    public Func<TimeZone> TimeZoneProvider = () => TimeZone.CurrentTimeZone;

    public void MethodToTest()
    {
        var timeZone = TimeZoneProvider();
        // Do something with the time zone
    }
}

[TestMethod]
public void Test()
{
    // Arrange
    var sut = new ClassToTest();
    sut.TimeZoneProvider = () => ... // return the time zone you would like for the test

    // Act
    sut.MethodToTest();

    // Assert
    // ...
}

EDIT: Another alternative would be to use constructor injection to pass a time zone into your class:

public class ClassToTest
{
    private readonly TimeZone _timeZone;
    public ClassToTest(TimeZone timeZone)
    {
        _timeZone = timeZone;
    }

    public void MethodToTest()
    {
        // Do something with _timeZone
    }
}

[TestMethod]
public void Test()
{
    // Arrange
    var timeZone = ... // return the time zone you would like for the test
    var sut = new ClassToTest(timeZone);

    // Act
    sut.MethodToTest();

    // Assert
    // ...
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501586

It's not entirely clear what you mean.

Do you use the current time zone of the system? If so, I suggest you include some sort of intermediary static property which can be reset just for tests to let you "pretend" that you're in a different time zone just for the duration of a test. Admittedly it means you have to be scrupulous about always using that property.

I dare say there's a Win32 system call you could use to change the system time zone, but that sounds a bit drastic - it's a shame there's no idea of the current time zone of a thread like there is for cultures :( (There's TimeZoneInfo.Local, but there's no managed way of changing that, as far as I've seen.)

If you're not using the local time zone, just make sure that your API takes all the information you need to write tests, so you can make sure that if you process dates and times in particular time zones, you get the right answer. If it would be useful to you, I can think up some good corner cases to test against. In particular, there are time zones where there's no local midnight once a year (when daylight savings stops) which can screw up some cases.

Upvotes: 7

Related Questions