In .NET (VB or C#) and using Microsoft.VisualStudio.TestTools.UnitTesting
for Unit testing:
How do I effectively change the locale decimal separator locally within a unit test so as String.Format("{0:0.0}", aDouble)
(which AFAIK is locale-dependent) would generate strings with the modified locale?
EDIT: Observe: I am not asking how to output text with an specific locale. I am asking how to change the decimal separator of locale within a unit test so as to simulate what will happen in a system that has a different decimal separator. I am not calling to String.Format from within the unit test code, String.Format is being called from within the tested functionality.
Additional information:
I am creating a .NET library in VB and I have one class MyClass
with an Encode(...)
function that is writing, among other things, numeric information as text.
The component will be used in an environment where different computers might have different configuration for the "decimal separator" (comma or point). My component, should however be insensitive to this, meaning that it should always output "point" (for example by making use of the System.Globalization.CultureInfo.InvariantCulture
when formatting numbers).
I wanted to write a unit test to ensure that the encoding functionality will continue to work even when the system locale decimal separator is set to "comma" instead of "point". I did some research and came up with something like this:
Public Sub Encode_CultureWithCommaSeparator_OutputMatchesTemplate() ... Dim oldCulture = Threading.Thread.CurrentThread.CurrentCulture ' A culture that uses "," as decimal separator Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("es-ES") CompareEncodedToTemplate(...) Threading.Thread.CurrentThread.CurrentCulture = oldCulture End Sub
The CompareEncodedToTemplate
function will use the MyClass.Encode
method to write the information to a MemoryStream
that then will be compared to a Template text file line per line, and the test will fail when they are not equal.
What I wanted to "simulate" was how the Encode
function would operate when the locale has decimal separator different than "point". Apparently my test function is not working as I expected:
I ran the test in a computer where the decimal separator i set to point, and the test succeed, so I thought "my encode function will work as I want, because the test passed".
However then I ran the test in a computer with the decimal separator set to comma, and the test failed. I realized that this was because in my Encode
logic I had missed to use the InvariantCulture
when formatting a double. That means that my test was not working as expected, because I should have been able to detect this situation the first computer (as it was the reason for which I wanted to create the test).
Thank you in advance.