How to mock DateTime.Now in unit tests

added by tparvi
3/6/2012 2:05:30 PM

5 Kicks, 483 Views

Different ways to mock DateTime.Now in unit tests


3/6/2012 2:05:40 PM
Could you provide an example of why it might be necessary to mock DateTime.Now? Thanks!

3/6/2012 10:36:59 PM
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.