Search code examples
unit-testing.net-coremoqmicrosoft-fakes

How to Mock Static property or method in dotnetcore 2.0 unit test


I used MS Fake framework in MSTest2 projects in .net framework to mock static member,such as

System.DateTime.Now

Are there equivalent framework can do the same thing as Fake in dotnet core 2.0?


Solution

  • Firstly let me tell that you cannot mock DateTime.Now as 'Now' is a static property. The main idea of mocking is to decouple the dependency and that dependency should be injected to corresponding classess to mock it. It means you have to implement an interface to the dependend class and that inteface should inject to the class where is consuming the dependent class. For unit testing Mock the same interface. So interface will never fit with Static as interface will always expect a concreate class type and you have to instantiate the class which implements the same interface.

    Having that said, if you are using MSTest there is a concept called Shim (I am not a big fan of Shim though ). You can create fake assembly. In your case you can create fake assembly of 'System' and Fake DateTime like below,

    [TestMethod]  
        public void TestCurrentYear()  
        {  
            int fixedYear = 2000;  
    
            // Shims can be used only in a ShimsContext:  
            using (ShimsContext.Create())  
            {  
              // Arrange:  
                // Shim DateTime.Now to return a fixed date:  
                System.Fakes.ShimDateTime.NowGet =   
                () =>  
                { return new DateTime(fixedYear, 1, 1); };  
    
                // Instantiate the component under test:  
                var componentUnderTest = new MyComponent();  
    
              // Act:  
                int year = componentUnderTest.GetTheCurrentYear();  
    
              // Assert:   
                // This will always be true if the component is working:  
                Assert.AreEqual(fixedYear, year);  
            }  
        }  
    

    To Shim or to create a Fake assembly you need visual studio ultimate and above.

    Please read more about shim here