Benny Meade
Benny Meade

Reputation: 612

Webdriver & .Net - TimeZoneInfo.ClearCachedData() does not clear TimeZone cache

The application I'm automating requires a unique reference number every time I fill out a form, and I do this in most of my tests using DateTime.Now as my unique reference number:

public static string Today = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

When I run these tests via Visual Studio for each test I get a unique DateTime.Now; which is correct behaviour. But when I run the same tests via Nunit GUI or TeamCity CI the DateTime.Now is cached from the first test run and therefore all tests there after fail.

I attempted to use TimeZoneInfo.ClearCachedData() in my TearDown section after each test run:

    [AfterScenario]
    public static void TearDown()
    {
        CultureInfo.CurrentCulture.ClearCachedData();
        TimeZoneInfo.ClearCachedData();
        driver.Quit();
    }

But this does not clear the cache when I run via Nunit GUI or TeamCity. I have tried using DateTime.UtcNow and also moving the ClearCachedData code in the setup section, but neither of these options work for me.

Has anyone overcome this issue before?

Upvotes: 0

Views: 267

Answers (1)

Arran
Arran

Reputation: 25076

This is because the static field will be initialized once and then keep it's value.

You have since removed the static part, you didn't need to necessarily do that. Just make it a property so that it's value is generated on every access:

public static string Today { get { return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); } }

NUnit's GUI and TeamCity will launch the whole suite in one thread. So the static field you had originally will literally be loaded only once and keep it's value.

Upvotes: 1

Related Questions