单位测试:DateTime.Now [英] Unit Testing: DateTime.Now

查看:138
本文介绍了单位测试:DateTime.Now的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些单元测试,期望'当前时间'不同于DateTime.Now,我不想更改计算机的时间,显然。实现这一点的最佳策略是什么?



谢谢

解决方案

最佳策略是将当前时间包含在抽象中,并将该抽象注入到消费者中






或者,您还可以将时间抽象定义为环境上下文

  public abstract class TimeProvider 
{
private static TimeProvider current =
DefaultTimeProvider.Instance;

public static TimeProvider当前
{
get {return TimeProvider.current;
set
{
if(value == null)
{
throw new ArgumentNullException(value);
}
TimeProvider.current = value;
}
}

public abstract DateTime UtcNow {get; }

public static void ResetToDefault()
{
TimeProvider.current = DefaultTimeProvider.Instance;
}
}

这将使您能够像这样使用它: / p>

  var now = TimeProvider.Current.UtcNow; 

在单元测试中,您可以替换 TimeProvider.Current 带有一个Test Double / Mock对象。使用Moq的示例:

  var timeMock = new Mock< TimeProvider>(); 
timeMock.SetupGet(tp => tp.UtcNow).Returns(new DateTime(2010,3,11));
TimeProvider.Current = timeMock.Object;

但是,当使用静态状态进行单元测试时,始终记住 strong>通过调用 TimeProvider.ResetToDefault()


I have some unit tests that expects the 'current time' to be different than DateTime.Now and I don't want to change the computer's time, obviously. What's the best strategy to achieve this?

Thanks

解决方案

The best strategy is to wrap the current time in an abstraction and inject that abstraction into the consumer.


Alternatively, you can also define a time abstraction as an Ambient Context:

public abstract class TimeProvider
{
    private static TimeProvider current =
        DefaultTimeProvider.Instance;

    public static TimeProvider Current
    {
       get { return TimeProvider.current; }
       set 
       {
           if (value == null)
           {
               throw new ArgumentNullException("value");
           }
           TimeProvider.current = value; 
       }
   }

   public abstract DateTime UtcNow { get; }

   public static void ResetToDefault()
   {    
       TimeProvider.current = DefaultTimeProvider.Instance;
   }            
}

This will enable you to consume it like this:

var now = TimeProvider.Current.UtcNow;

In a unit test, you can replace TimeProvider.Current with a Test Double/Mock object. Example using Moq:

var timeMock = new Mock<TimeProvider>();
timeMock.SetupGet(tp => tp.UtcNow).Returns(new DateTime(2010, 3, 11));
TimeProvider.Current = timeMock.Object;

However, when unit testing with static state, always remember to tear down your fixture by calling TimeProvider.ResetToDefault().

这篇关于单位测试:DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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