2017-09-22 23 views

回答

0

首先讓我告訴你不能嘲笑DateTime.Now,因爲'Now'是一個靜態屬性。嘲笑的主要思想是將依賴關係分解,並且應該將相關性注入相應的類別中以嘲笑它。這意味着你必須實現一個到依賴類的接口,並且該接口應該向正在消耗依賴類的類注入。對於單元測試模擬相同的界面。因此,接口將永遠不適合靜態,因爲接口將始終期望concreate類類型,並且必須實例化實現相同接口的類。如果你使用MSTest,有一個叫做Shim的概念(我不是Shim的粉絲)。您可以創建假裝配。你的情況,你可以創建「系統」和假的DateTime像下面的假裝配,

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

要墊片或創建你需要的Visual Studio Ultimate和上述假裝配。

請閱讀更多關於墊片的信息here

+1

這不是答案。 .net核心不支持MSFakes。 – sjdirect

相關問題