Created
June 15, 2016 23:13
-
-
Save davidalpert/ca452cd67cc8d567247a1b70d619ef5a to your computer and use it in GitHub Desktop.
Spoof the current CultureInfo in a unit test.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SpoofCulture : IDisposable | |
{ | |
private readonly CultureInfo _previousCultureInfo; | |
private readonly Thread _threadToSpoof; | |
public SpoofCulture(CultureInfo cultureToUse, Thread threadToSpoof = null) | |
{ | |
_threadToSpoof = threadToSpoof ?? Thread.CurrentThread; | |
_previousCultureInfo = CultureInfo.CurrentCulture; | |
_threadToSpoof.CurrentCulture = cultureToUse; | |
} | |
public void Dispose() | |
{ | |
_threadToSpoof.CurrentCulture = _previousCultureInfo; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SpoofCultureTests | |
{ | |
[Test] | |
public void Can_spoof_the_current_culture_on_the_current_thread() | |
{ | |
var cultureBeforeSpoofing = CultureInfo.CurrentCulture; | |
var cultureToSpoof = CultureInfo.GetCultures(CultureTypes.SpecificCultures).First(); | |
if (cultureToSpoof.Equals(cultureBeforeSpoofing)) | |
{ | |
cultureToSpoof = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Skip(1).First(); | |
} | |
Assert.AreEqual(CultureInfo.CurrentCulture, cultureBeforeSpoofing); | |
Assert.AreNotEqual(CultureInfo.CurrentCulture, cultureToSpoof); | |
using (new SpoofCulture(cultureToSpoof)) | |
{ | |
Assert.AreEqual(CultureInfo.CurrentCulture, cultureToSpoof); | |
Assert.AreNotEqual(CultureInfo.CurrentCulture, cultureBeforeSpoofing); | |
} | |
Assert.AreEqual(CultureInfo.CurrentCulture, cultureBeforeSpoofing); | |
Assert.AreNotEqual(CultureInfo.CurrentCulture, cultureToSpoof); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment