日期和格式一直是我的噩梦。 最近我正在写大量的文件,其中日期必须转换为各种格式的字符串(取决于客户端)。
我想创建一个可以整合很多的单元测试,只是举几个例子。
以下测试失败,因为“3 月 9 日”和“3 月 9 日”不匹配。我如何让这个测试文化感知。 更好地测试任何人?
[TestCase("March 09", "{0:m}")]
[TestCase("March, 2008", "{0:y}")]
[TestCase("3/9/2008 4:05 PM", "{0:g}")
public void When_stringFormat_a_date_should_match(string expected,string format)
{
DateTime dt = new DateTime(2008, 03, 09, 16, 05, 07);
string actual = String.Format(format, dt);
assert ??
}
最佳答案
您正在调用 String.ToString()
!指定 CultureInfo
(甚至使用此函数)没有意义,因为它总是返回独立于指定区域性的原始字符串。
IMO 你必须在转换日期时指定 CultureInfo
,即
string actual = String.Format(CultureInfo.InvariantCulture, format, dt);
Assert.AreEqual(expected, actual);
关于c# - 使用 string.Format 和 UnitTest 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7695908/