If you persist a DateTime property to SQL Server you lose a tiny bit of precision. For most use cases this will go unnoticed. However, if you try to compare two objects as part of an integration test, your test will fail. Let us look how we can work around the different timer precisions between .Net and SQL Server in Fluent Assertions.
Given we have an order and persist it to our database. When we retrieve this orderFromDb, it should be the same as the initial order:
1 2 |
orderFromDb.Should().BeEquivalentTo(order); # => test fails because objects are not equivalent |
Unfortunately, this snipped results in a failed test, then all DateTime properties are a few milliseconds off.
Luckily for us, Fluent Assertions allows us to modify the equivalency comparison behaviour and we can use the BeCloseTo() method with an allowed delta in milliseconds:
1 2 3 4 |
orderFromDb.Should().BeEquivalentTo(order, options => options .Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000)) .WhenTypeIs<DateTime>()); # => test passes as long as the difference is 1 second or less |
It is not the most understandable syntax, but it does the job and you do not need to write your own code to do a delta comparison.