Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server integration test validating datetime created with AutoFixture

I am creating integration test for my repository. I use AutoFixture to create a Notification which should be inserted with a NotificationRepository.

Notification has a property Processed which is a DateTime. When AutoFixture creates the date, it is created with very precise values.

SQL Server does not have the same precision as .Net so you sometimes miss a millisecond when inserting the date into SQL Server and so my test has a hard time validationg the result. I use semantic comparison to check if the inserted value is correct.

How can I configure AutoFixture to create dates with the same precision as SQL Server?

Current code

[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; }
}
like image 662
Jakob Avatar asked Dec 28 '25 19:12

Jakob


1 Answers

The built-in DateTime value type has the precision it has, and you can't change that. It's a type defined by the BCL so AutoFixture can't change its precision. If you can't use DATETIME2(3) as suggested by @marc_s in the comments, your repository implementation will exhibit loss of precision, and your tests need to take that into account.

One way to do that is to add a custom comparer of DateTime values that has a built-in tolerance factor. You could, for example, implement IEqualityComparer<DateTime>.

Some assertion libraries allow you to pass in a custom IEqualityComparer<T>; e.g. xUnit.net. This would enable you to write something like:

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

where TolerantDateTimeComparer is your custom implementation of IEqualityComparer<DateTime>.

like image 150
Mark Seemann Avatar answered Dec 30 '25 07:12

Mark Seemann