Create or get specific SPTimeZone instance

C#Unit TestingSharepointSharepoint 2013

C# Problem Overview


What is the most convenient way to create a specific instance of Microsoft.SharePoint.SPTimeZone as the following one:

SPTimeZone utc = SPRegionalSettings.GlobalTimeZones
	                               .OfType<SPTimeZone>()
	                               .FirstOrDefault(tz => tz.Information.Bias == 0
                                                   && tz.Information.DaylightBias == 0);

Is this hack the best one I can get...

This is in particular a problem for me, since I would like to mock this part of code for unit testing and to force it to always return UTC. The property GlobalTimeZones seems to depend on HttpContext.Current or an actual request - a prerequisite I don't have in my Unit Tests...

N.B: I know that there is System.TimeZoneInfo but a third party assembly forces me into using SPTimeZone ...

C# Solutions


Solution 1 - C#

To stop the discussion I decided to finally answer this question on my own.

There are several really helpful solutions in the comments which I want to gather in this short answer:

  • Introducing a facade / adapter
  • MS Fakes or other frameworks to
    • fake access to SPTimeZone
    • create a fake HttpContext
  • go with the hack described in the question above ...

I for my part decided to go with MSFakes to shim the whole 3rd party call (since I didn't wan't to test its behavior anyways) and to shim all properties of SPTimeZone that I use in my method. Introducing an adapter unfortunately wasn't an option for me, since I had to preserve the (internal) API.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkusView Question on Stackoverflow
Solution 1 - C#MarkusView Answer on Stackoverflow