How to test logic which is dependent on current date

前端 未结 8 1453
名媛妹妹
名媛妹妹 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.

提交回复
热议问题