测试日期时间相等时,为什么这个单元测试失败? [英] Why does this unit test fail when testing DateTime equality?
本文介绍了测试日期时间相等时,为什么这个单元测试失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在.NET 3.5使用NUnit的2.2,使用DateTime.Equals当下列测试失败。为什么呢?
[的TestFixture]
公共类AttributeValueModelTest
{
公共类HasDate
{
公开日期时间?则DateValue
{
得到
{
DateTime值;
返回DateTime.TryParse(ObjectValue.ToString(),超时值)?值:新的datetime();?
}
}
公共对象ObjectValue {获得;组; }
}
[测试]
公共无效TwoDates()
{
DateTime的实际= DateTime.Now;
VAR日期=新HasDate {ObjectValue =实际};
Assert.IsTrue(date.DateValue.Value.Equals(实际));
}
}
解决方案
日期是不相等的。下降的TryParse一些蜱。比较刻度值。
对于一次测试运行:
Console.WriteLine(date.DateValue.Value.Ticks);
Console.WriteLine(actual.Ticks);
收益率:
633646934930000000
633646934936763185
Using NUnit 2.2 on .NET 3.5, the following test fails when using DateTime.Equals. Why?
[TestFixture]
public class AttributeValueModelTest
{
public class HasDate
{
public DateTime? DateValue
{
get
{
DateTime value;
return DateTime.TryParse(ObjectValue.ToString(), out value) ? value : new DateTime?();
}
}
public object ObjectValue { get; set; }
}
[Test]
public void TwoDates()
{
DateTime actual = DateTime.Now;
var date = new HasDate {ObjectValue = actual};
Assert.IsTrue(date.DateValue.Value.Equals(actual));
}
}
解决方案
The dates aren't equal. TryParse drops some ticks. Compare the Tick values.
For one test run:
Console.WriteLine(date.DateValue.Value.Ticks);
Console.WriteLine(actual.Ticks);
Yields:
633646934930000000
633646934936763185
这篇关于测试日期时间相等时,为什么这个单元测试失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文