【问题标题】:SQL Server integration test validating datetime created with AutoFixtureSQL Server 集成测试验证使用 AutoFixture 创建的日期时间
【发布时间】: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


【解决方案1】:

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

一种方法是添加具有内置容差因子的DateTime 值的自定义比较器。例如,您可以实现IEqualityComparer&lt;DateTime&gt;

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

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

其中TolerantDateTimeComparer 是您对IEqualityComparer&lt;DateTime&gt; 的自定义实现。

【讨论】:

  • 谢谢你,马克,很好的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多