我在C#中构建了一个Windows服务,它根据当前日期和时间从数据库中调用实时时间序列数据。
我在测试数据库中有测试数据,我想使用这些数据来计算数据是否以正确的方式使用。
我想知道是否有人使用过应用程序,或者有任何其他方法可以将系统日期“模拟”到您的本地计算机上。例如,我可以运行此应用程序并将其设置为将我的系统日期设置为指定的日期。
任何建议都是很棒的。
发布于 2012-06-19 19:30:21
只需将对DateTime.Now属性的访问封装在接口后面即可。
public interface IDateTimeProvider
{
DateTime Now { get; }
}在您的代码中,使用如下实现:
public class DateTimeProvider : IDateTimeProvider
{
public DateTime Now { get { return DateTime.Now; } }
}对于您的测试,您可以通过创建测试类或使用模拟框架来模拟IDateTimeProvider。
如果您将此接口与依赖注入等技术结合使用,则很容易更改服务的行为,即使在运行时也是如此。
例如,您可以创建一个始终处于空闲状态的IDateTimeProvider:
public class AlwaysToLateDateTimeProvider : IDateTimeProvider
{
public DateTime Now { get { return DateTime.Now.AddHours(-2); } }
}或者创建一个从文件、数据库、管道等读取“模拟的”datetime的实现。
在测试时,您可以将服务配置为使用这些实现之一,而在实时模式下运行时,只需将依赖项注入配置为使用返回“正确”日期时间的普通实现即可。
当然还有TypeMock Isolator...
Isolate.WhenCalled(() => DateTime.Now).WillReturn(new DateTime(2008, 1, 1));发布于 2012-06-19 18:56:21
我已经使用它来覆盖现在,例如,在运行测试时。在使用DateTime.Now的实际实现中,您将使用新的SystemTime.Now。在测试中,您只需将Now设置为另一个返回您选择的值的函数即可。
public static class SystemTime
{
private static Func<DateTime> now = () => DateTime.Now;
public static Func<DateTime> Now
{
get { return now; }
set { now = value; }
}
}测试中的示例用法:
SystemTime.Now = () => DateTime.Now.AddMinutes(20);在单元测试拆卸中,用SystemTime.Now = () => DateTime.Now重新设置它是很重要的
正常用法:
DateTime now = SystemTime.Now();发布于 2015-08-18 16:34:37
与Mharlin的解决方案非常相似,下面的实现提供了DateTime.Now的一对一替换。添加的是一些在单元测试中操纵时间的方便方法。修改的是需要显式执行返回DateTime的操作,这更类似于DateTime.Now的用法。
public static class SystemTime
{
private static Func<DateTime> now = () => DateTime.Now;
public static DateTime Now
{
get { return now(); }
}
public static void Set(DateTime dt)
{
now = () => dt;
}
public static void MoveForward(TimeSpan ts)
{
var dt = now().Add(ts);
Set(dt);
}
public static void Reset()
{
now = () => DateTime.Now;
}
}生产代码中的示例用法:
var twentyMinutesFromNow = SystemTime.Now.AddMinutes(20);时间敏感测试中的示例用法(此测试验证缓存过期时间):
// Set(): effectively lock the system clock at a specific time
SystemTime.Set(new DateTime(2015, 1, 1));
RunCodeThatFetchesDataAndCachesIt();
// MoveForward(): easily move the clock relative to current time with an
// arbitrary TimeSpan
SystemTime.MoveForward(TimeSpan.FromMinutes(1));
RunCodeThatFetchesDataAndCachesIt();
VerifyExpectationThatDataWasFetchedTwice();
// Reset(): return to the normal behavior of returning the current
// DateTime.Now value
SystemTime.Reset();https://stackoverflow.com/questions/11099406
复制相似问题