How to test logic which is dependent on current date

前端 未结 8 1429
名媛妹妹
名媛妹妹 2020-12-20 16:52

I have this method which is dependent on current date. It checks if today is Sun, Mon, Tue or Wed, then it gives 5 days of lead time for arrival of shipped items. If its Thu

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 17:16

    Generally speaking, you'd want to abstract the method of obtaining the current date and time behind an interface, eg:

    public interface IDateTimeProvider
    {
        DateTime Now { get; }
    }
    

    The real service would be:

    public class DateTimeProvider: IDateTimeProvider
    {
        public DateTime Now
        {
            get
            {
                return DateTime.Now;
            }
        }
    }
    

    And a test service would be:

    public class TestDateTimeProvider: IDateTimeProvider
    {
        private DateTime timeToProvide;
        public TestDateTimeProvider(DateTime timeToProvide)
        {
            this.timeToProvide = timeToProvide;
        }
    
        public DateTime Now
        {
            get
            {
                return timeToProvide;
            }
        }
    }
    

    For services that require the current time, have them take an IDateTimeProvider as a dependency. For the real thing, pass a new DateTimeProvider(); when you're a component, pass in a new TestDateTimeProvider(timeToTestFor).

提交回复
热议问题