【发布时间】:2015-11-12 22:09:06
【问题描述】:
我正在为我的存储库创建集成测试。我使用AutoFixture 创建一个Notification,它应该插入一个NotificationRepository。
Notification 有一个属性Processed,它是一个DateTime。当AutoFixture 创建日期时,它是用非常精确的值创建的。
SQL Server 的精度与 .Net 不同,因此在将日期插入 SQL Server 时有时会错过一毫秒,因此我的测试很难验证结果。我使用语义比较来检查插入的值是否正确。
如何配置 AutoFixture 以创建与 SQL Server 精度相同的日期?
当前代码
[Test]
public void InsertShouldInsertNotification()
{
var sut = new NotificationRepository(TestConnectionString);
var notification = fixture.Build<Notification>().Without(x => x.Id).Create();
sut.Insert(notification);
var result = sut.Get(notification.Id);
notification.AsSource().OfLikeness<Notification>().ShouldEqual(result);
}
public enum DocumentStatus
{
New = 0,
InSigning = 1,
Cancelled = 2,
Signed = 3,
InReview = 4,
Reviewed = 5,
Deleted = 6,
Rejected = 7
}
public class Notification
{
public int Id { get; set; }
public string DocumentId { get; set; }
public string DocumentName { get; set; }
public string Notes { get; set; }
public string Metadata { get; set; }
public DocumentStatus Status { get; set; }
public DateTime? Processed { get; set; }
}
【问题讨论】:
-
如果您使用的是 SQL Server 2008 或更高版本,则应使用
DATETIME2(3)而不是DATETIME以获得与 .NET 相同的毫秒精度。DATETIME的精度为 3.33 毫秒 -DATETIME2(n)的精度最高可达 7 位,如果需要,最高可达 100 纳秒。n = 3对应毫秒精度 -
内置的
DateTime值类型具有它所具有的精度,您无法更改它。它是 BCL 定义的类型,因此 AutoFixture 无法更改其精度。如果您不能按照@marc_s 的建议使用DATETIME2(3),您的存储库实现将表现出精度损失,您的测试需要考虑到这一点。 -
感谢您的回答,DATETIME2(3) 听起来不错。
标签: c# sql-server integration-testing autofixture