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

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

问题描述

我有一些单元测试,预计当前时间比DateTime.Now不同,我不想更改计算机的时间,很明显。什么是实现这一目标的最佳策略?

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?

感谢

推荐答案

的策略是的把当前时间的抽象,并注入了抽象进入消费

或者的,你也可以定义一个抽象的时间作为周围语境

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;

在一个单元测试,你可以用一个测试双人/模仿对象替换 TimeProvider.Current 。使用起订量例如:

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;

不过,与静态的单元测试,总是通过调用记得拆掉你的灯具 TimeProvider.ResetToDefault()

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

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