Friday September 30th

Thursday September 29th

How to mock DateTime.Now in unit tests

Different ways to mock DateTime.Now in unit tests


Could you provide an example of why it might be necessary to mock DateTime.Now? Thanks!

One example from previous project: In the UI we had an option to search for things that are older than x days/minutes. Basically the server receives call "Give me 10 latests records that are older than 10 minutes". In this case it is easier to test the system when I can mock DateTime.Now.

But basically any code that deals with current time: schedulers, scheduled tasks, different kind of alarms etc. When you write test for the functionality it is pretty easy to spot these. Usually if you don't mock the DateTime.Now it is more difficult to write the test.

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network