Skip to content

Commit d34555e

Browse files
committed
test: add TZ mocker and tests
1 parent 27812cf commit d34555e

3 files changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using System;
2+
using System.Reflection;
3+
4+
namespace NetCoreForce.Client.Tests
5+
{
6+
/// <summary>
7+
/// Sample TimeZone IDs for use in tests
8+
/// </summary>
9+
public static class TimeZoneIds
10+
{
11+
public static string TimeZoneIdNewYork = "America/New_York";
12+
public static string TimeZoneIdPhoenix = "America/Phoenix";
13+
public static string TimeZoneIdLondon = "Europe/London";
14+
public static string TimeZoneIdTokyo = "Asia/Tokyo";
15+
}
16+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System;
2+
using System.Reflection;
3+
4+
namespace NetCoreForce.Client.Tests
5+
{
6+
public class LocalTimeZoneInfoMocker : IDisposable
7+
{
8+
public LocalTimeZoneInfoMocker(TimeZoneInfo mockTimeZoneInfo)
9+
{
10+
var info = typeof(TimeZoneInfo).GetField(
11+
"s_cachedData",
12+
BindingFlags.NonPublic | BindingFlags.Static
13+
);
14+
15+
var cachedData = info.GetValue(null);
16+
17+
var field = cachedData.GetType().GetField(
18+
"_localTimeZone",
19+
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Instance
20+
);
21+
22+
field.SetValue(cachedData, mockTimeZoneInfo);
23+
}
24+
25+
public void Dispose()
26+
{
27+
TimeZoneInfo.ClearCachedData();
28+
}
29+
}
30+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using Xunit;
4+
using NetCoreForce.Client;
5+
using NetCoreForce.Client.Models;
6+
7+
namespace NetCoreForce.Client.Tests
8+
{
9+
public class TimeZoneInfoMockerTests
10+
{
11+
[Fact]
12+
public void TestLocalTimeZoneInfoMocker()
13+
{
14+
TimeSpan mockedUtcOffset;
15+
TimeSpan actualLocalUtcOffset = TimeZoneInfo.Local.BaseUtcOffset;
16+
17+
using (new LocalTimeZoneInfoMocker(TimeZoneInfo.FindSystemTimeZoneById(TimeZoneIds.TimeZoneIdPhoenix)))
18+
{
19+
// shifted to Phoenix TZ
20+
Assert.Equal(TimeZoneIds.TimeZoneIdPhoenix, TimeZoneInfo.Local.Id);
21+
mockedUtcOffset = TimeZoneInfo.Local.BaseUtcOffset;
22+
Assert.NotEqual(TimeZoneInfo.Local.BaseUtcOffset, actualLocalUtcOffset);
23+
}
24+
25+
// back to local machine's TZ
26+
Assert.NotEqual(TimeZoneInfo.Local.Id, TimeZoneIds.TimeZoneIdPhoenix);
27+
Assert.NotEqual(TimeZoneInfo.Local.BaseUtcOffset, mockedUtcOffset);
28+
}
29+
30+
}
31+
}

0 commit comments

Comments
 (0)