测试 C# 中的 DateTime 解析是否失败?
我在单元测试运行期间解析日期时遇到问题,但无法重现它。 更有趣的是,当测试由持续集成过程运行时,它会失败,但在 Visual Studio 中运行时会成功,并且它们都在同一台计算机上运行,尽管使用不同的用户。
这是测试:(
[Test]
public void Test()
{
DateTime.Parse("21/12/2009", CultureInfo.CreateSpecificCulture("it-IT"));
}
在意大利语中,短日期格式为 dd/MM/yyyy)
我期望它失败的原因是我修改了机器上的国际设置,以便意大利文化的短日期模式为 dd /MM/yy,但看起来它要么没有正确拾取它,要么足够聪明,无论如何都能够解析它,至少当我手动运行它时。
有什么想法如何让测试失败吗?
I have an issue with parsing a date during a unit test run, but I cannot reproduce it.
To make it more interesting it fails when the test is run by a continuous integration process but succeeds when run within Visual Studio, and they both run on the same machine, although with a different user.
Here's the test:
[Test]
public void Test()
{
DateTime.Parse("21/12/2009", CultureInfo.CreateSpecificCulture("it-IT"));
}
(In Italian the short date format is dd/MM/yyyy)
The reason I'd expect it to fail is that I have the international settings on the machine modified so that the short date pattern for the Italian culture is dd/MM/yy, but it looks like it is either not picking it up correctly or smart enough to be able to parse it anyway, at least when I run it manually.
Any ideas how to make the test fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
即使您使用的是 CultureInfo 对象,DateTime.Parse 也会根据多种模式尝试您的字符串,以尽量避免引发异常。魔鬼在于细节 - 您可能应该查看 DateTime.Parse 的文档深入。
“无论如何,足够聪明来解析它”可能就是正在发生的事情。您应该使用
ParseExact
并显式提供格式字符串以使其失败。Even if you're using a CultureInfo object, DateTime.Parse will try your string against several patterns to do it's best to avoid throwing an exception. The devil is in the details - you should probably look at the documentation for DateTime.Parse in depth.
"Smart enough to parse it anyway" is probably what is happening. You should use
ParseExact
and explicitly provide the format string to make it fail.不要让您的测试依赖于基于用户配置文件的服务器设置。相反,尝试这种方法:
Don't let your tests depend on user-profile-based server settings. Instead, try this approach:
所以...如果我错了请纠正我,但是不是每个用户的区域设置吗?因此,如果您修改两个用户的设置,测试应该是一致的...
好的,尝试打印出框架认为两个用户的日期模式,这里是 doco:
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo_members.aspx< /a>
尝试
CultureInfo.DateTimeFormatInfo.ShortDatePattern
,我认为这就是dd/mm/yy(yy)
。So... Correct me if I am wrong, but aren't the locale settings per user? So if you modify the settings for both users the tests should be consistent...
OK, try to print out what the framework thinks is the date pattern on both users, here is the doco:
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo_members.aspx
Try
CultureInfo.DateTimeFormatInfo.ShortDatePattern
, i think that's whatdd/mm/yy(yy)
is.您的配置中有全球化设置吗?
do you have a globalization setting in your config?