What's a good way to overwrite DateTime.Now during testing?

后端 未结 11 1198
一个人的身影
一个人的身影 2020-11-28 02:52

I\'ve got some (C#) code that relies on today\'s date to correctly calculate things in the future. If I use today\'s date in the testing, I have to repeat the calculation in

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:14

    Using Microsoft Fakes to create a shim is a really easy way to do this. Suppose I had the following class:

    public class MyClass
    {
        public string WhatsTheTime()
        {
            return DateTime.Now.ToString();
        }
    
    }
    

    In Visual Studio 2012 you can add a Fakes assembly to your test project by right clicking on the assembly you want to create Fakes/Shims for and selecting "Add Fakes Assembly"

    Adding Fakes Assembly

    Finally, Here is what the test class would look like:

    using System;
    using ConsoleApplication11;
    using Microsoft.QualityTools.Testing.Fakes;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace DateTimeTest
    {
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestWhatsTheTime()
        {
    
            using(ShimsContext.Create()){
    
                //Arrange
                System.Fakes.ShimDateTime.NowGet =
                () =>
                { return new DateTime(2010, 1, 1); };
    
                var myClass = new MyClass();
    
                //Act
                var timeString = myClass.WhatsTheTime();
    
                //Assert
                Assert.AreEqual("1/1/2010 12:00:00 AM",timeString);
    
            }
        }
    }
    }
    

提交回复
热议问题