How to test logic which is dependent on current date

前端 未结 8 1432
名媛妹妹
名媛妹妹 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:17

    One "common" way of doing so is to "fake" the current system date (that can be done in several ways) and then test your code on "known" dates.

    Another interesting way is to change your implementation slightly to:

    private DateTime GetEstimatedArrivalDate()
    {
        return GetEstimatedArrivalDate(DateTime.Now);
    }
    
    private DateTime GetEstimatedArrivalDate(DateTime forDate)
    {
        DateTime estimatedDate; 
        if (forDate.DayOfWeek >= DayOfWeek.Thursday)
        {
            estimatedDate = forDate.Date.AddDays(6);
        }
        else
        {
            estimatedDate = forDate.Date.AddDays(5);
        }
        return estimatedDate; 
    }
    

    And then use the method with a parameter to test on "immediate" dates.

    0 讨论(0)
  • 2020-12-20 17:20

    Seems like there are a limited enough number of cases that you could test them each explicitly. The method depends on today's date, but the output depends only on the day of week, and every date has a day of week.

    0 讨论(0)
提交回复
热议问题