C# 模拟日期时间

本文关键字:时间 日期 模拟 | 更新日期: 2023-09-27 18:33:30

我想模拟日期时间。假设我有要执行的操作列表,每个操作都有一个日期时间字段。当该日期时间到来时,应执行该操作。我可以使用日期时间检查日期时间;但是我如何模拟日期时间。我的意思是如果当前时间是下午 2 点。行动应该在下午4点,5点进行。我可以使用模拟当前时间到下午 4 点,将执行第一个操作,一小时后将执行第二个操作。

谢谢

C# 模拟日期时间

前段时间我发布了一些关于以这种方式测试日期的方法:

http://ivowiblo.wordpress.com/2010/02/01/how-to-test-datetime-now/

希望对你有帮助

实现此目的的最简单方法是将系统时钟更改为"测试时间",运行测试,然后更改回来。 这很笨拙,我真的不推荐它,但它会起作用。

更好的方法是在DateTime.Now上使用抽象,这将允许您注入静态值或操作检索到的值进行测试。鉴于您希望测试值"滴答",而不是保持静态快照,最简单的方法是向"now"添加TimeSpan

因此,添加一个名为"偏移量"的应用程序设置,可以解析为TimeSpan

<appSettings>
    <add key="offset" value="00:00:00" />
</appSettings>

,然后在每次检索此值时将此值添加到DateTime.Now

public DateTime Time
{ 
    get 
    { 
        var offset = TimeSpan.Parse(ConfigurationManager.AppSettings["offset"]);
        return DateTime.Now + offset;
    }
}

要在将来运行此 1 小时 20 分钟,您只需调整offset

<add key="offset" value="01:20:00" />

理想情况下,你会为DateTime创建一个接口并实现依赖注入,但为了你的目的 - 尽管这是首选 - 我建议这打开的蠕虫罐会为你创造一个混乱的世界。这很简单,可以工作。

这实际上是一个复杂的问题,但幸运的是有一个解决方案:野田时间。

最简单的方法是注释掉检查 DateTime.Now 的部分,并创建一个可以调用的新方法/属性,该方法/属性将返回一组脚本化的时间。

例如:

class FakeDateTime
{
    private static int currentIndex = -1;
    private static DateTime[] testDateTimes = new DateTime[]
        {
            new DateTime(2012,5,8,8,50,10),
            new DateTime(2012,5,8,8,50,10)  //List out the times you want to test here
        };
    /// <summary>
    /// The property to access to check the time.  This would replace DateTime.Now.
    /// </summary>
    public DateTime Now
    {
        get
        {
            currentIndex = (currentIndex + 1) % testDateTimes.Length;
            return testDateTimes[currentIndex];
        }
    }
    /// <summary>
    /// Use this if you want to specifiy the time.
    /// </summary>
    /// <param name="timeIndex">The index in <see cref="testDateTimes"/> you want to return.</param>
    /// <returns></returns>
    public DateTime GetNow(int timeIndex)
    {
        return testDateTimes[timeIndex % testDateTimes.Length];
    }
}

如果您想要更具体(或更好(的答案,请提供一些代码示例。