• 单元测试mock当前时间


    在实际项目中很多地方用到DateTime.Now,这个时间是时时变化的。如果要进行单元测试对比预期结果时,这个时间无法预测,可以添加如下两个时间类

    namespace Common.Helper
    {
        /// <summary>
        /// 获取当前时间
        /// However, when unit testing with static state, always remember to tear down your fixture by calling .
        /// </summary>
        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 Now { get; }
    
            public static void ResetToDefault()
            {
                TimeProvider.current = DefaultTimeProvider.Instance;
            }
        }
        public class DefaultTimeProvider : TimeProvider
        {
            private readonly static DefaultTimeProvider instance =
                new DefaultTimeProvider();
    
            private DefaultTimeProvider() { }
    
            public override DateTime Now
            {
                get { return DateTime.Now; }
            }
    
            public static DefaultTimeProvider Instance
            {
                get { return DefaultTimeProvider.instance; }
            }
        }
    }
    View Code

    在实际代码中使用方法:

    var now = TimeProvider.Current.Now;

    单元测试模拟方法:

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

    需要用到moq4模拟对象

  • 相关阅读:
    windows nginx
    stdClass 标准
    array_merge
    array_pop
    array_push
    array_unique
    GMT与UTC简介(转)
    curl-手册
    13.5. zipfile — Work with ZIP archives
    7. Input and Output
  • 原文地址:https://www.cnblogs.com/missile/p/7065831.html
Copyright © 2020-2023  润新知