在最近发现由于在将文本解析为数字时未指定 InvariantCulture
而导致的错误之后,我想加强我们的单元测试,以便他们能够发现问题。我编写了一个新测试,将当前区域性更改为具有不同数字格式的区域性,重新运行现有测试方法之一,然后将区域性设置回去。不幸的是,文化变革也影响了其他测试方法。有没有一种方法可以让测试不交互?
我确实发现将文化设置测试放在文件的最后会“解决”问题,但我讨厌依赖测试顺序,因为它不能保证。
在以下示例中,系统文化为 "en-EN"
时,TestMethod1
和 TestMethod2
自行运行将成功。如果我同时运行所有方法,它们都会失败。
[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);
}
}
最佳答案
[TestMethod]
public void FooTest()
{
var foo = new Foo();
var actual = ExecuteWithCulture(() => foo.Bar(), "en-US");
}
private T ExecuteWithCulture<T>(Func<T> methodFunc, string cultureName)
{
T result = default(T);
var thread = new Thread(() =>
{
result = methodFunc();
});
thread.CurrentCulture = new CultureInfo(cultureName);
thread.Start();
thread.Join();
return result;
}
关于c# - 如何为单个 MSTest 测试方法设置区域性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382843/