In C#, how do I keep certain method calls out of the codebase entirely?

后端 未结 6 1089
迷失自我
迷失自我 2021-01-01 23:54

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 t

6条回答
  •  星月不相逢
    2021-01-02 00:36

    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!
        }
    }
    

提交回复
热议问题