【问题标题】:How to Mock Static property or method in dotnetcore 2.0 unit test [closed]如何在 dotnetcore 2.0 单元测试中模拟静态属性或方法 [关闭]
【发布时间】:2017-09-22 01:12:58
【问题描述】:

我在.net框架的MSTest2项目中使用MS Fake框架来模拟静态成员,例如

System.DateTime.Now

dotnet core 2.0 中是否有等效的框架可以做与 Fake 相同的事情?

【问题讨论】:

  • 这怎么算离题?

标签: unit-testing .net-core moq microsoft-fakes


【解决方案1】:

首先让我告诉您,您不能模拟 DateTime.Now,因为“Now”是一个静态属性。模拟的主要思想是解耦依赖,并且应该将依赖注入到相应的类中来模拟它。这意味着您必须为依赖类实现一个接口,并且该接口应该注入到使用依赖类的类中。用于单元测试模拟相同的接口。所以接口永远不会适合静态接口,因为接口总是期望一个concreate类类型,你必须实例化实现相同接口的类。

话虽如此,如果您使用的是 MSTest,则有一个名为 Shim 的概念(虽然我不是 Shim 的忠实粉丝)。您可以创建假程序集。在您的情况下,您可以像下面这样创建“系统”和假日期时间的假程序集,

[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);  
        }  
    }  

要 Shim 或创建 Fake 程序集,您需要 Visual Studio Ultimate 及更高版本。

请阅读更多关于 shim here

【讨论】:

  • 这不是答案。 .net 核心不支持 MSFakes。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多