How to Check if Two DateTimes Are Close in Fluent Assertions

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:

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:

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.