Ilia G
Ilia G

Reputation: 10221

Overriding DateTime.Now

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.

Upvotes: 3

Views: 3633

Answers (2)

João Angelo
João Angelo

Reputation: 57718

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.

Upvotes: 12

codymanix
codymanix

Reputation: 29520

There is no way in pure .net, you need to call Win32SetSystemTime function using pinvoke

Upvotes: -1

Related Questions