[英]how should i create my own 'now' / DateTime.Now?
i'm starting to build a part of a system which will hold a lot of DateTime validations, and a lot of 'if it was done before now' or 'if it will start in an hour etc'. 我正在开始构建系统的一部分,该部分将包含很多DateTime验证,以及很多“如果在现在之前完成”或“如果要在一小时内启动等等”。
Usual way to go is to use DateTime.Now to get the actual time . 通常的方法是使用DateTime.Now获取实际时间 。
I predict however, that during unit test that will give me a real headache because i will have to setup my testdata for the time when the test will run in stead of use a default set of test data. 但是我预测,在单元测试期间,这将使我非常头疼,因为我将不得不在测试运行时设置测试数据,而不是使用默认的测试数据集。 So i thought: why not use my own 'now' so i can set the current datetime to any moment in time. 所以我想:为什么不使用自己的“现在”,这样我就可以将当前日期时间设置为任何时间。 As i don't want to set the testservers internal clock i was thinking about this solution, and i was wondering what you think of it. 由于我不想设置测试服务器的内部时钟,因此我在考虑此解决方案,我想知道您对此有何看法。 Base thought is that i use my own DateTime class. 基本思想是我使用自己的DateTime类。 That class gives you the current datetime, but you can also set your own time from outside. 该类为您提供当前的日期时间,但是您也可以从外部设置自己的时间。
public static class MyDateTime
{
private static TimeSpan _TimeDifference = TimeSpan.Zero;
public static DateTime Now
{
get
{
return DateTime.Now + _TimeDifference;
}
}
public static void SetNewNow(DateTime newNow)
{
_TimeDifference = newNow - DateTime.Now;
}
public static void AddToRealTime(TimeSpan timeSpan )
{
_TimeDifference = timeSpan;
}
public static void SubtractFromRealTime(TimeSpan timeSpan)
{
_TimeDifference = - timeSpan;
}
}
Some time ago i already read something about it. 前一段时间,我已经读过一些有关它的信息。 A short search for mock DateTime.Now with your favorite search engine should reveal enough links. 用您最喜欢的搜索引擎短暂搜索模拟DateTime.Now ,应该会显示足够的链接。
This seems to look quite interesting: http://blog.typemock.com/2009/05/mockingfaking-datetimenow-in-unit-tests.html 这看起来似乎很有趣: http : //blog.typemock.com/2009/05/mockingfaking-datetimenow-in-unit-tests.html
what do u mean ? 你是什么意思 ? if u need any specialization, so u can use Extension methods ! 如果您需要任何专业知识,则可以使用扩展方法! easily write an extension method for DateTime class and do whatever u need. 轻松地为DateTime类编写扩展方法,并执行所需的任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.