After recently finding an error that was due to not specifying InvariantCulture
when parsing text into numbers, I wanted to beef up our unit tests so that they would catch the issue. I wrote a new test that changed the current culture to one with different numeric formatting, re-ran one of the existing test methods, then set the culture back. Unfortunately, the culture change also affected other test methods. Is there a way to do this such that the tests do not interact?
I did find that putting the culture-setting test last in the file would "solve" the problem, but I hate to rely on the test ordering since it's not guaranteed.
In the following example, with a system culture of "en-EN"
, TestMethod1
and TestMethod2
will succeed if run by themselves. If I run all of the methods together, they all fail.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethodGerman()
{
var originalCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
TestMethod1();
Thread.CurrentThread.CurrentCulture = originalCulture;
}
[TestMethod]
public void TestMethod1()
{
double value = Double.Parse("3.00");
Assert.AreEqual(value, 3.0);
}
[TestMethod]
public void TestMethod2()
{
double value = Double.Parse("4.00");
Assert.AreEqual(value, 4.0);
}
}