功能的单元测试挑战

时间:2019-05-29 04:58:22

标签: c# unit-testing nunit stub

在使用Nunit的单元测试文件中,我试图编写测试用例,以测试所有if / else分支。 在单元测试中调用该方法时,是否可以在该方法中注入特定的DateTime.Now
该方法需要餐厅的开/关时间。

public void LunchDinnerBummer(string openingTime, string closingTime)
{
    //Based on the current time, alerts the user
    //if it is lunch/dinner time or outside of 
    //business hours
    var openTime = DateTime.Parse(openingTime);
    var closeTime = DateTime.Parse(closingTime);

    //End of lunch time
    var lunchTime = DateTime.Parse("3:00 PM");

    //For lunch time
    if (openTime < DateTime.Now && DateTime.Now < lunchTime)
        Console.WriteLine("It is time to go to Ted’s for lunch!");

    //For dinner time
    else if (DateTime.Now > lunchTime && DateTime.Now < closeTime)
        Console.WriteLine("It is time to go to Ted’s for dinner!");

    //If outside of business hour before Opening Time for today
    else if (DateTime.Now < openTime)
    {
        TimeSpan span = openTime.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
    //If outside of business hours past closing time for today
    //Calculate for the hours and minutes left till opening time for next day
    else
    {
        var openTimeNextDay = openTime.AddDays(1);
        TimeSpan span = openTimeNextDay.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
}

1 个答案:

答案 0 :(得分:2)

一种方法(最好的IMO)是简单地将当前时间作为参数传递。

public void LunchDinnerBummer(string openingTime, string closingTime, DateTime now)
...

然后您的测试可以使用各种不同的时间,而您的生产代码可以通过DateTime.Now。

除了提出的问题之外,我猜想LunchDinnerBummer可能是代表餐厅的某个类的方法。如果是这样,我将在构造函数中初始化打开和关闭时间,将LunchDinnerBummer简化为单个参数。

更多您没问过的内容:-) ...为什么使用string而不是DateTime作为参数?