我有一些测试代码执行文化感知转换的规范。我想为我的测试设置一个定义的文化,这样我就可以对预期的值进行硬编码,而不必担心运行测试的系统的配置文化。
有没有一种简单的方法可以使用Machine.Specifications来执行此操作,还是必须设置Thread.CurrentThread.CurrentCulture
(以及可能CurrentUICulture
)?
答案 0 :(得分:6)
MSpec没有任何内置工具来更改Thread的文化。但是,它有几种在测试之前和之后做“某事”的一般方法。
“简单”的方法是使用“建立和清理”代表。
[Subject("Culture Sensitive Tests")]
public class When_doing_culture_sensitive_stuff
{
Establish context = () =>
{
OldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = NewCulture;
Thread.CurrentThread.CurrentUICulture = NewCulture;
}
Cleanup cleanup = () =>
{
Thread.CurrentThread.CurrentCulture = OldCulture;
Thread.CurrentThread.CurrentUICulture = OldCulture;
}
Because of = () => Subject.DoSomethingCultureSensitive();
It should_do_something_culture_sensitive = () => ...;
private static CultureInfo OldCulture;
private static CultureInfo NewCulture;
}
但是,您需要在每个需要它的测试中分享它。所以,我推荐一个帮助类进行切换。
public class ChangeCurrentCulture : IDisposable
{
private readonly CultureInfo original;
public ChangeCurrentCulture(CultureInfo culture)
{
original = Thread.CurrentThread.CurrentCulture;
Change(culture)
}
private void Change(CultureInfo culture)
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
public void Dispose()
{
Change(original);
}
}
您可以在共享基类中设置调用。代表们在运行规范时会被链接。
public abstract class CultureSensitive
{
Establish context = () =>
{
Change = new ChangeCurrentCulture(NewCulture);
}
Cleanup cleanup = () =>
{
Change.Dispose();
}
private static ChangeCurrentCulture Change;
private static CultureInfo NewCulture;
}
[Subject("Culture Sensitive Tests")]
public class When_doing_culture_sensitive_stuff : CultureSensitive
{
Because of = () => Subject.DoSomethingCultureSensitive();
It should_do_something_culture_sensitive = () => ...;
}
另一个选项取决于您将所有培养敏感测试分成单独的程序集。 IAssemblyContext
接口为您提供了两种程序集范围的设置和清理方法。您可以更改该程序集中所有规范的文化(不要担心清理)。
public class CultureSensitiveTests : IAssemblyContext
{
public void OnAssemblyStart()
{
Thread.CurrentThread.CurrentCulture = NewCulture;
Thread.CurrentThread.CurrentUICulture = NewCulture;
}
public void OnAssemblyComplete()
{
}
}