【问题标题】:Unit Test Challenge For a Function函数的单元测试挑战
【发布时间】:2019-05-29 04:58:21
【问题描述】:

在我使用 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 ");
    }
}

【问题讨论】:

  • 引用的问题更笼统,即如何使用 DateTime.Now 进行测试。这是一个相当具体的例子,有几个可能的具体答案。

标签: c# unit-testing nunit stub


【解决方案1】:

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

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

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

超出所问的问题,我猜LunchDinnerBummer 可能是代表餐厅的某个类的方法。如果是这种情况,我会在构造函数中初始化打开和关闭时间,将LunchDinnerBummer 简化为单个参数。

更多你没有问的东西 :-) ... 为什么使用 string 而不是 DateTime 作为参数?

【讨论】:

  • selenium Web 驱动程序将打开和关闭时间捕获为字符串/文本。然后将这些值传递给LunchDinnerBummer()。是的,我想更改签名以使其变得直截了当。
  • 我想我会比这更进一步并注入一些接口IClock,它提供了一个方法DateTime TimeNow(),所以在你的单元测试中你可以模拟你需要时钟的值返回,而不是将另一个参数暴露给真正不需要的方法。
  • @LordWilmore 是的,我很确定他最终会被驱使。我通常已经养成了将这些东西记在脑海中的习惯,直到我真正确定界面会是什么样子,但是现在就这样做并稍后更改也不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 2016-06-06
  • 2012-05-14
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
相关资源
最近更新 更多