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

后端 未结 11 1252
一个人的身影
一个人的身影 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:22

    You could inject the class (better: method/delegate) you use for DateTime.Now in the class being tested. Have DateTime.Now be a default value and only set it in testing to a dummy method that returns a constant value.

    EDIT: What Blair Conrad said (he has some code to look at). Except, I tend to prefer delegates for this, as they don't clutter up your class hierarchy with stuff like IClock...

提交回复
热议问题