我正在重构一些单元测试,发现某些解析策略依赖于DateTime.TryParseExact
和sbyte.TryPase
,而它们本身依赖于NumberFormatInfo.CurrentInfo
和DateTimeFormatInfo.CurrentInfo
。
为了使我的单元测试正确安排,我决定通过以下方式将CurrentInfo
和NumberFormatInfo
的{{1}}属性设置为其不变的风格:
DateTimeFormatInfo
但是,出于好奇,我试图通过单元测试来检查各个CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
是否已设置,但事实并非如此。我想知道在这两个InvariantInfo
InvariantCulture
的问题
CurrentInfo
了解基本实现:
[Fact]
public void ShouldReturnInvariantInfo()
{
CultureInfo.CurrentCulture.NumberFormat = NumberFormatInfo.InvariantInfo;
CultureInfo.CurrentCulture.DateTimeFormat = DateTimeFormatInfo.InvariantInfo;
NumberFormatInfo.CurrentInfo.Should().Be(NumberFormatInfo.InvariantInfo);
DateTimeFormatInfo.CurrentInfo.Should().Be(DateTimeFormatInfo.InvariantInfo);
}
:
NumberFormatInfo.InvariantInfo
public static NumberFormatInfo CurrentInfo
{
get
{
CultureInfo currentCulture = CultureInfo.CurrentCulture;
if (!currentCulture._isInherited)
{
NumberFormatInfo numInfo = currentCulture.numInfo;
if (numInfo != null)
return numInfo;
}
return (NumberFormatInfo) currentCulture.GetFormat(typeof (NumberFormatInfo));
}
}
:
DateTimeFormatInfo.CurrentInfo
答案 0 :(得分:3)
如果我理解正确,那么您想在Current
的区域性下运行一些代码(测试),但NumberFormat
和DateTimeFormat
除外。如果您遇到这种情况,建议您Invariant
当前的区域性并修改克隆:
Clone
让我们来看看格式
// Current culture clone
CultureInfo testCulture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
// modified: current culture except Number and DateTime which are Invariant
testCulture.NumberFormat = CultureInfo.InvariantCulture.NumberFormat;
testCulture.DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// and, finally, set back as current
CultureInfo.CurrentCulture = testCulture;
结果:
Console.Write(ReferenceEquals(CultureInfo.CurrentCulture.DateTimeFormat,
CultureInfo.InvariantCulture.DateTimeFormat)
? "Equals"
: "Not Equals");
编辑:为了运行修改后的区域性代码Equals
,我们可以为其实现一个 class :
using
然后按如下所示使用它:
public class TestCulture : IDisposable {
private CultureInfo m_SavedCulture;
private CultureInfo m_TestCulture;
private bool m_IsDisposed;
public TestCulture() {
m_SavedCulture = CultureInfo.CurrentCulture;
m_TestCulture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
m_TestCulture.NumberFormat = CultureInfo.InvariantCulture.NumberFormat;
m_TestCulture.DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
CultureInfo.CurrentCulture = m_TestCulture;
}
protected vitrual void Dispose(bool disposing) {
if (disposing) {
if (!m_IsDisposed && ReferenceEquals(CultureInfo.CurrentCulture, m_TestCulture)) {
CultureInfo.CurrentCulture = m_SavedCulture;
m_IsDisposed = true;
}
}
}
public void Dispose() => Dispose(true);
}