Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding DateTime.Now

Tags:

.net

time

When we do development/QA we often need to pretend that current date/time is something other than now. It is pretty common for us to have some sort of logic that relies on date.

Simple example: say a product in the store is available between Dec 15 2010 to Jan 3 2011. These two dates would be stored in DB, and code would compare it to DateTime.Now. This obviously needs to be [unit]tested somehow. Question is how?

So far we just added a custom Date object and attempted to enforce using Date.Now instead of DateTime.Now, which does not cover any third party code that may rely on current date and is also feels super lame.

I wonder is there is a bit more kosher way of handling date override without changing system date in Windows.

like image 523
Ilia G Avatar asked Dec 03 '25 08:12

Ilia G


1 Answers

For unit testing I would recommend you to take a look at Microsoft Moles, an isolation framework that would let you replace a call to DateTime.Now with your own delegate which could return any date you wanted.

like image 121
João Angelo Avatar answered Dec 06 '25 00:12

João Angelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!