如何测试取决于当前日期的逻辑 [英] How to test logic which is dependent on current date

查看:34
本文介绍了如何测试取决于当前日期的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此方法,具体取决于当前日期.它会检查今天是星期天,星期一,星期二还是星期三,然后给出5天的交货时间.如果是周四,周五或周六,则需要6天的交货时间来说明周末.

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 Thur, Fri or Sat then it gives 6 days of lead time to account for the weekend.

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

实际的估计逻辑更为复杂.为了这个问题,我已经简化了它.我的问题是,如何根据今天的日期编写类似这样的内容的单元测试?

The actual estimation logic is more complex. I have simplified it for the purpose of this question. My question is how do I write a unit test for something like this which depends on todays date?

推荐答案

您需要将当前日期作为参数传递:

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...

请注意,这还修复了程序中潜在的错误,该错误在两次调用 DateTime.Now 的两次调用之间更改日期.

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

这篇关于如何测试取决于当前日期的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆