简体   繁体   English

将.NET DateTime转换为SQL DateTime值

[英]Unit testing .NET DateTime to SQL DateTime values

When I run this code: 当我运行此代码时:

var data = "test";
var timestamp = DateTime.Now;
var id = repo.InsertNewRecord(data, timestamp);
var record = repo.GetRecord(id);

Assert.AreEqual(data, record.Data);
Assert.AreEqual(timestamp, record.TimeStamp);

... it fails on the second assertion. ...它在第二个断言上失败。

The expected timestamp has a tick count of 635449135145624472, but the value I'm receiving from the database has a tick count of 635449135140000000. This is understandable because .NET DateTime values have an accuracy of 100ns while SQL Server DateTime only has a accuracy of 3.33ms. 预期的时间戳的滴答计数为635449135145624472,但是我从数据库接收的值的滴答计数为635449135140000000。这是可以理解的,因为.NET DateTime值的精度为100ns,而SQL Server DateTime的精度为3.33。女士。 I don't really need to be the timestamps to be more accurate than that, but is there a standard way of testing the inputs and outputs for equality? 我实际上并不需要成为比其更准确的时间戳,但是是否存在测试输入和输出是否相等的标准方法?

Obtaining a timestamp from the database is one way to do it: 从数据库获取时间戳是一种方法:

var timestamp = Session.CreateSQLQuery("SELECT GetDate()").UniqueResult<DateTime>();

Don't test at tick level, you could use a particular format to test the dates eg 不要在刻度级别测试,您可以使用特定格式来测试日期,例如

var dateFmt = "dd-MM-yyyy hh:mm:ss";
Assert.AreEqual(timestamp.ToString(dateFmt), record.TimeStamp.ToString(dateFmt));

Or alternatively, you could do that but just add some room for variance 或者,您可以这样做,但只需添加一些差异空间

Assert.True((timeStamp - record.TimeStamp).TotalMilliseconds < 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM