SQL 服务器集成测试验证使用 AutoFixture 创建的日期时间

SQL Server integration test validating datetime created with AutoFixture

我正在为我的存储库创建集成测试。我使用 AutoFixture 创建一个 Notification,应该用 NotificationRepository 插入。

Notification 有一个 属性 Processed,这是一个 DateTime。当 AutoFixture 创建日期时,它是用非常精确的值创建的。

SQL 服务器的精度与 .Net 不同,因此在将日期插入 SQL 服务器时有时会错过一毫秒,因此我的测试很难验证结果。我使用语义比较来检查插入的值是否正确。

如何配置 AutoFixture 以创建与 SQL 服务器具有相同精度的日期?

当前代码

[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; }
}

内置的 DateTime 值类型具有它所具有的精度,您无法更改它。它是由 BCL 定义的类型,因此 AutoFixture 无法更改其精度。如果您不能按照评论中@marc_s 的建议使用 DATETIME2(3),您的存储库实现将表现出精度损失,您的测试需要考虑到这一点。

实现此目的的一种方法是添加具有内置容差因子的 DateTime 值的自定义比较器。例如,您可以实施 IEqualityComparer<DateTime>.

一些断言库允许您传入自定义 IEqualityComparer<T>;例如xUnit.net。这将使您能够编写如下内容:

Assert.Equal(expected, actual, new TolerantDateTimeComparer());

其中 TolerantDateTimeComparer 是您对 IEqualityComparer<DateTime> 的自定义实现。