重写DateTime.Now [英] 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.
简单的例子:假设商店中的产品在2010年12月15日到2011年1月3日之间可用.这两个日期将存储在数据库中,并且代码会将其与 DateTime.Now
进行比较.显然,这需要以某种方式进行[单元]测试.问题是如何?
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?
到目前为止,我们只是添加了一个自定义的 Date
对象,并尝试使用 Date.Now
而不是 DateTime.Now
强制实施,涵盖可能依赖于当前日期的任何第三方代码,并且感觉超级super脚.
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.
我想知道在Windows中在不更改系统日期的情况下还有更多类似的方式来处理日期覆盖.
I wonder is there is a bit more kosher way of handling date override without changing system date in Windows.
推荐答案
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.
这篇关于重写DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!