Question

MbUnit has a great attribute: MultipleCultureAttribute.

I am wondering if there is an easy way to do this in MSTest? So far, the best I can come up with is:

  • Externalizating the actual test code to a private method
  • Saving the current culture
  • Setting the culture and calling the private method (repeated for each culture)
  • And finally, reverting to the original culture

At best, it can be described as ugly ... and verbose.

Was it helpful?

Solution

The simplest approach may be to use an anonymous delegate, however keep in mind that MSTest will treat this as a single test so it may be difficult to distinguish results for different cultures.

eg. Rough code for anonymous delegate approach.

public static class MultipleCultures
{
    public static void Do(Action action, params CultureInfo[] cultures)
    {
        CultureInfo originalCulture = Thread.CurrentCulture;

        try
        {
            foreach (CultureInfo culture in cultures)
            {
                Thread.CurrentCulture = culture;

                try
                {
                    action();
                }
                catch
                {
                    Console.WriteLine("Failed while running test with culture '{0}'.", culture.Name);
                    throw;
                }
            }
        }
        finally
        {
            Thread.CurrentCulture = originalCulture;
        }
    }
}

[TestClass]
public class Fixture
{
    [TestMethod]
    public void Test()
    {
        MultipleCultures.Do(() =>
        {
            // test code...
        }, CultureInfo.InvariantCulture, CultureInfo.GetCulture("en-GB"));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top