What's a good way to overwrite DateTime.Now during testing?

后端 未结 11 1193
一个人的身影
一个人的身影 2020-11-28 02:52

I\'ve got some (C#) code that relies on today\'s date to correctly calculate things in the future. If I use today\'s date in the testing, I have to repeat the calculation in

11条回答
  •  清酒与你
    2020-11-28 03:00

    I'd suggest using IDisposable pattern:

    [Test] 
    public void CreateName_AddsCurrentTimeAtEnd() 
    {
        using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))
        {
            string name = new ReportNameService().CreateName(...);
            Assert.AreEqual("name 2010-12-31 23:59:00", name);
        } 
    }
    

    In detail described here: http://www.lesnikowski.com/blog/index.php/testing-datetime-now/

提交回复
热议问题