开发者

how should i create my own 'now' / DateTime.Now?

i'm starting to build a part of a system which will hold a lot of DateTime validations, and a lot of 'if it was done before now' or 'if it will start in an hour etc'.

Usual way to go is to use DateTime.Now to get the actual time.

I predict however, that during unit test that will give me a real headache because i will have to setup my testdata for the time when the test will run in stead of use a default set of test data. So i thought: why not use my own 'now' so i can set the current datetime to any moment in time. As i don't want to set the testservers internal clock i was thinking about this solution, and i was wondering what you think of it. Base thought is that i use my own DateTime class. That class gives you the current datetime, but you can also set your own time from outside.

 public static class MyDate开发者_C百科Time
    {
        private static TimeSpan _TimeDifference = TimeSpan.Zero;
        public static DateTime Now
        {
            get
            {
                return DateTime.Now + _TimeDifference;
            }
        }
        public static void SetNewNow(DateTime newNow)
        {
            _TimeDifference = newNow - DateTime.Now;
        }
        public static void AddToRealTime(TimeSpan timeSpan )
        {
            _TimeDifference =  timeSpan;
        }
        public static void SubtractFromRealTime(TimeSpan timeSpan)
        {
            _TimeDifference =  - timeSpan;
        }
    }


Some time ago i already read something about it. A short search for mock DateTime.Now with your favorite search engine should reveal enough links.

This seems to look quite interesting: http://blog.typemock.com/2009/05/mockingfaking-datetimenow-in-unit-tests.html


what do u mean ? if u need any specialization, so u can use Extension methods ! easily write an extension method for DateTime class and do whatever u need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜