我有以下单元测试我将.Net Framework库移植到.Net核心xunint测试库。需要添加单元测试的项目是
https://github.com/dotliquid/dotliquid
正在添加到所选文件中,如此处所示
我想添加的单元测试是
[Test]
public void ParsingWithCommaDecimalSeparatorShouldWork()
{
var ci = new CultureInfo(CultureInfo.CurrentCulture.Name)
{
NumberFormat =
{
NumberDecimalSeparator = ","
, NumberGroupSeparator = "."
}
};
Thread.CurrentThread.CurrentCulture = ci;
var t = Template.Parse("{{2.5}}");
var result = t.Render( new Hash(), CultureInfo.InvariantCulture );
Assert.AreEqual( result, "2.5" );
}
然而,测试无法在dotnet核心中编译。
严重级代码描述项目文件行抑制状态 错误CS1061“线程”不包含的定义 'CurrentCulture'并没有扩展方法'CurrentCulture'接受a 可以找到'Thread'类型的第一个参数(你错过了吗? 使用指令或程序集 引用?)DotLiquid.Tests(net451)C:\ Users \ phelan \ workspace \ dotliquid \ src \ DotLiquid.Tests \ OutputTests.cs 113 N / A
我需要对不同的文化进行不同的单元测试。我想创建一个XUnit理论,其中每个实例都在不同的文化中传递单元测试以进行验证。这是如何在.NetCore中完成的?
答案 0 :(得分:5)
我查看了一些dotnet source,我找到了这个。
CultureInfo.DefaultThreadCurrentCulture = ci;
基本上,您可以从CultureInfo
的静态属性设置默认线程当前区域性,而不是从Thread.CurrentThread
public CultureInfo CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return CultureInfo.CurrentCulture;
}
set
{
Contract.EndContractBlock();
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentCulture.set.
if (m_CurrentCulture == null && m_CurrentUICulture == null)
nativeInitCultureAccessors();
CultureInfo.CurrentCulture = value;
}
}
这是Thread.cs
。因此,您可以明确设置CultureInfo.CurrentCulture
属性。
示例:
CultureInfo.CurrentCulture = new CultureInfo("en-GB"); ;
Assert.Equal("£1,000.00", String.Format("{0:C}", 1000));
CultureInfo.CurrentCulture = new CultureInfo("en-US"); ;
Assert.Equal("$1,000.00", String.Format("{0:C}", 1000));
单元测试项目的csproj文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<IsPackable>false</IsPackable>
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0-preview-20170425-07" />
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
</ItemGroup>
</Project>
答案 1 :(得分:0)
解决方案是设置
CultureInfo.DefaultThreadCurrentCulture = ci;
和然后启动新线程。这将为下一个线程设置当前文化。最后的测试案例是。
[Test]
public void ParsingWithCommaDecimalSeparatorShouldWork()
{
var ci = new CultureInfo(CultureInfo.CurrentCulture.Name)
{
NumberFormat =
{
NumberDecimalSeparator = ","
, NumberGroupSeparator = "."
}
};
CultureInfo.DefaultThreadCurrentCulture = ci;
var result = "";
var thread = new Thread
( delegate()
{
Console.WriteLine(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
Console.WriteLine(CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator);
var t = Template.Parse("{{2.5}}");
result = t.Render(new Hash(), CultureInfo.InvariantCulture);
} );
thread.Start();
thread.Join();
Assert.AreEqual(result, "2.5");
}
这有点乱,但完成工作。