How to test logic which is dependent on current date

前端 未结 8 1428
名媛妹妹
名媛妹妹 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条回答
  •  -上瘾入骨i
    2020-12-20 16:54

    You need to pass the current date in as a parameter:

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

    In real code you call it like this:

    DateTime estimatedDate = GetEstimatedArrivalDate(DateTime.Now.Date);
    

    Then you can test it as follows:

    DateTime actual = GetEstimatedArrivalDate(new DateTime(2010, 2, 10));
    DateTime expected = ...;
    // etc...
    

    Note that this also fixes a potential bug in your program where the date changes between consecutive calls to DateTime.Now.

提交回复
热议问题