I'm trying to get rid of all DateTime.Now
method calls and replace them with my own GetNow()
method, which may sometimes return a fixed date for testing purposes.
How can I enforce that no one adds a DateTime.Now
call in the future? Can I use NDepend or StyleCop to check this on my continuous integration server?
With NDepend it is very easy to write this rule:
// <Name>Forbid DateTime.Now, use xxx.GetNow() instead</Name>
WARN IF Count > 0 IN
SELECT METHODS WHERE
IsDirectlyUsing "OPTIONAL:System.DateTime.get_Now()"
Notice:
Also, to generate the original query...
SELECT METHODS WHERE
IsDirectlyUsing "OPTIONAL:System.DateTime.get_Now()"
...just right-click DateTime.get_Now() and choose Select methods ... that are directly using me
Firstly, DateTime.Now
is a property.
That means you don't need to put parenthesis after call.
Secondly, if by testing purposes you mean a framework like NUnit, you might want to check out Microsoft Moles which allows you to substitute any static method call with your own custom implementation while testing. Heck, it's cool:
[Test]
[ExpectedException (typeof (Y2KBugException))]
public void TestY2KBug ()
{
MDateTime.NowGet = () => new DateTime (2001, 1, 1);
Bomb.DetonateIfY2K ();
}
public static class Bomb {
public static void DetonateIfY2K ()
{
if (DateTime.Now == new DateTime (2001, 1, 1))
throw new Y2KBugException (); // take cover!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With