单元测试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; } } } }
在实际代码中使用方法:
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模拟对象