什么是测试过程中覆盖DateTime.Now的好办法? [英] What's a good way to overwrite DateTime.Now during testing?

查看:111
本文介绍了什么是测试过程中覆盖DateTime.Now的好办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些(C#)code,它依赖于今天的日期来正确计算在未来的事情。如果我使用今天的日期在测试中,我要重复的测试,感觉不对的计算。什么是设定日期到测试中的已知值,这样我可以测试结果是一个已知的价值的最佳方法是什么?

I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?

推荐答案

我的preference是有使用时间其实靠接口类,比如

My preference is to have classes that use time actually rely on an interface, such as

interface IClock
{
    DateTime Now { get; } 
}

通过一个具体的实施

class SystemClock: IClock
{
     DateTime Now { get { return DateTime.Now; } }
}

然后,如果你愿意,你可以提供任何其他类型的时钟你想进行测试,如

Then if you want, you can provide any other kind of clock you want for testing, such as

class StaticClock: IClock
{
     DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }
}

有可能在提供的时钟依赖于它的类一些开销,但是这可以通过任何数目依赖注入溶液(使用控制的容器中,普通的旧的构造/ setter注入,或甚至一个的反转处理<一href=\"http://$c$cbetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx\">Static网关模式)。

There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a Static Gateway Pattern).

提供一个对象或提供所需时间也工作方法的其他机制,但我认为关键是要避免重置系统时钟,因为这只是打算在其他级别的介绍疼痛。

Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels.

此外,使用 DateTime.Now 键,包括它在你的计算不只是感觉不对 - 它剥夺了你的测试特定时间的能力,例如,如果你会发现,只发生在半夜边界附近,或在星期二的错误。利用当前的时间不会让你测试的场景。或至少​​不每当你想要的。

Also, using DateTime.Now and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want.

这篇关于什么是测试过程中覆盖DateTime.Now的好办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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