語言

使用填充碼隔離您的應用程式以進行單元測試

Shim 類型,作為 Microsoft Fakes Framework 使用的兩大核心技術之一,在測試期間對應用程式元件進行隔離,是非常重要的。 它們的運作方式是攔截並轉移呼叫至特定方法,然後您可以直接在測試中導向自定義程序代碼。 此功能讓您能管理這些方法的結果,確保每次通話結果一致且可預測,無論外部條件如何。 這種控制層級可簡化測試程式,並協助達成更可靠且精確的結果。

當您需要在程式碼與不屬於您解決方案一部分的組件之間建立隔離邊界時,請使用 shims。 當目標是將解決方案的元件彼此隔離時,建議使用 存根 。 關於存根的詳細說明,請參見「 使用存根將應用程式的部分彼此隔離以進行單元測試」。

本文提供逐步指南,說明如何使用 shim 類型,將呼叫重新導向至單元測試程式碼中的特定方法。

了解使用 shim 時的類型限制

使用墊片時有一些限制。 它們無法用於 .NET 基底類別中某些函式庫的所有類型,具體如下:

  • .NET框架中的mscorlib 以及 System
  • System.Runtime 在 .NET Core 或 .NET 5+ 中使用

在設計測試策略時,請規劃此限制,以確保單元測試的成功與效能。

製作墊片

假設你的元件包含對 System.IO.File.ReadAllLines 該方法的呼叫:

// Code under test:
this.Records = System.IO.File.ReadAllLines(path);

要準備元件進行單元測試,請完成以下步驟。

建立類別程式庫

為班級庫建立一個新的解決方案和初始專案。

  1. 在 Visual Studio Start 視窗(File>Start Window)中,選擇 C# 或 Visual Basic 範本,建立一個 Class Library 專案。

    Visual Studio 中 .NET Framework 和 C# 的類別庫專案範本螢幕擷圖。

    2022 Visual Studio .NET Framework 與 C# 類別庫專案範本截圖。

  2. 設定新專案:

    • 將類別函式庫 Project name設為 HexFileReader。
    • 將 解決方案名稱 設為 ShimsTutorial。
    • 將 Target 框架設定為 .NET框架 4.8。

    選取 ,創建。

  3. 專案開啟後,在 方案總管 找到預設檔案 ,並刪除該檔案。

  4. 新增一個名為 HexFile.cs class 的檔案並輸入以下類別定義:

    // HexFile.cs
    public class HexFile
    {
        public string[] Records { get; private set; }
    
        public HexFile(string path)
        {
            this.Records = System.IO.File.ReadAllLines(path);
        }
    }
    

新增單元測試專案

在您的方案中新增另一個用於單元測試的專案。

  1. 在 方案總管 中,右鍵點擊 ShimsTutorial 解答,並選擇 Add>New Project。

  2. 在 開始視窗 中,選取範本以建立一個 Unit Test Project 專案。

    Visual Studio 中適用於 .NET Framework 和 C# 的 Microsoft 單元測試專案範本螢幕擷取畫面。

    Visual Studio 2022 .NET Framework 和 C# 的 Microsoft 單元測試專案範本截圖。

  3. 設定新專案:

    • 將單元測試 Project name設為 TestProject。
    • 將 Target 框架設定為 .NET框架 4.8。

    選取 ,創建。

新增Fakes組件

新增對 HexFileReader 專案的引用。

  1. 在 方案總管 中,展開 TestProject 節點,右鍵點擊 References 節點,選擇 Add Reference。

    顯示如何在 Visual Studio 中從單元測試專案將參考加入類別的螢幕擷取畫面。

     截圖,展示如何在 2022 Visual Studio 中將單元測試專案的參考資料加入課程。

    1. 在 參考資料管理器 視窗的左側窗格,選擇 專案 區塊。

    2. 在中間的窗格,選擇專案的勾選框 HexFileReader ,然後選擇 確定。

  2. 加上偽裝組件。

    1. 在 方案總管 中,找到組件的包含節點:

      • 對於較舊的 .NET Framework Project(非 SDK 風格),先展開單元測試project節點,然後展開 References節點。

      • 針對 .NET Framework、.NET Core 或 .NET 5+ 的 SDK 風格專案,請展開 Dependencies 節點,將要偽造的組件定位在 Assemblies、Projects 或 Packages。

      • 對於Visual Basic,請在方案總管工具列中選擇顯示所有檔案,以查看參考資料節點。

    2. 選擇包含 System 定義的 System.IO.File.ReadAllLines 組件。

    3. 右鍵點擊節點System,選擇新增假組裝。

      顯示如何在 Visual Studio 中為專案加入 Fakes 組件的螢幕擷取畫面。

      截圖,示範如何在 Visual Studio 2022 中為專案新增 Fakes 組件。

    建置過程會針對無法搭配 shims 使用的類型產生警告和錯誤。

    建置完成後,方案總管 會刷新,顯示單元測試專案的 Fakes 節點。

  3. 選取 Fakes\mscorlib.fakes 檔案,並將 XML 替換為可排除不受支援類型的內容:

    <Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
    <Assembly Name="mscorlib" Version="4.0.0.0"/>
    <StubGeneration>
         <Clear/>
    </StubGeneration>
    <ShimGeneration>
         <Clear/>
         <Add FullName="System.IO.File"/>
         <Remove FullName="System.IO.FileStreamAsyncResult"/>
         <Remove FullName="System.IO.FileSystemEnumerableFactory"/>
         <Remove FullName="System.IO.FileInfoResultHandler"/>
         <Remove FullName="System.IO.FileSystemInfoResultHandler"/>
         <Remove FullName="System.IO.FileStream+FileStreamReadWriteTask"/>
         <Remove FullName="System.IO.FileSystemEnumerableIterator"/>
    </ShimGeneration>
    </Fakes>
    

建立單元測試

為你的專案新增單元測試。

  1. 更新專案範本提供的預設 TestProject\UnitTest1.cs 檔案。

    在檔案中找到以下程式碼區段,並以提供的摘要替換:

    [TestMethod]
    public void TestMethod1()
    {
    }
    

    替換片段:

    [TestMethod]
    public void TestFileReadAllLine()
    {
       using (ShimsContext.Create())
       {
          // Arrange
          System.IO.Fakes.ShimFile.ReadAllLinesString = (s) => new string[] { "Hello", "World", "Shims" };
    
          // Act
          var target = new HexFile("this_file_doesnt_exist.txt");
    
          Assert.AreEqual(3, target.Records.Length);
       }
    }
    
  2. 要查看單元測試中所有假組件,請在方案總管選單欄中選擇顯示所有檔案:

    Visual Studio 2022 中方案總管的螢幕擷圖,顯示所有檔案,其中包含 Fakes 組件。

  3. 打開 測試檔案總管 並執行測試。

正確處置每個檔板上下文非常重要。 一般來說,請在 ShimsContext.Create 陳述式內呼叫 using 方法,以確保已註冊的 shim 能夠正確清除。 例如,你可以註冊一個測試方法的 shim,該方法會以 DateTime.Now 一個代理取代該方法,該代理總是回傳 2000 年 1 月 1 日。 如果您忘記在測試方法中清除已註冊的 shim,則該次測試執行的其餘部分一律會回傳 2000 年 1 月 1 日作為 DateTime.Now 的值。 這個結果可能會讓人感到驚訝和困惑。

檢視 shim 類別的命名慣例

Shim 類別名稱使用 Fakes.Shim 前綴加上原始型別名稱。 參數名稱會附加至方法名稱。 (你不必為 System.Fakes 新增任何組件參考。)

System.IO.File.ReadAllLines(path);

System.IO.Fakes.ShimFile.ReadAllLinesString = (path) => new string[] { "Hello", "World", "Shims" };

了解墊片的運作方式

填充碼的運作方式是將 繞道 引入要測試之應用程式的程式代碼基底。 每當呼叫原始方法時,Fakes 系統就會介入並重新導向該呼叫,使其改為執行你自訂的 shim 程式碼,而不是原始方法。

請務必注意,這些繞道會在運行時間動態建立和移除。 應在 ShimsContext 的生命週期內建立繞道。 當 ShimsContext 被處理時,裡面產生的任何活躍 Shims 也會被移除。 為了有效率地管理此設計,建議將 detour 的建立封裝在 using 陳述式中。

探索適用於不同方法的相容性墊片(shim)

Shim 支援各種類型的方法。

靜態方法

當你用 shim 靜態方法時,固定墊片的屬性會被歸類在 shim 類型中。 這些屬性僅僅具有一個 setter,用來將委派附加至目標方法。

例如,對於一個名為 MyClass 且具有靜態方法 MyMethod 的類別:

//Code under test
public static class MyClass {
    public static int MyMethod() {
        ...
    }
}

你可以將 shim 附加到 MyMethod,讓它固定回傳 5:

// Unit test code
ShimMyClass.MyMethod = () => 5;

實體方法(適用於所有實體)

就像靜態方法一樣,實例方法也可以對所有實例進行填補。 用來容納這些 Shim 的屬性會放在名為 AllInstances 的巢狀型別中,以避免混淆。

對於帶有實例方法MyClass的類別MyMethod:

// Code under test
public class MyClass {
    public int MyMethod() {
        ...
    }
}

你可以將 shim 附加到 MyMethod,使其無論是哪個實例,一律回傳 5:

// Unit test code
ShimMyClass.AllInstances.MyMethod = () => 5;

以下程式碼片段顯示了 ShimMyClass 所產生的型別結構:

// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
   public static class AllInstances {
      public static Func<MyClass, int>MyMethod {
         set {
            ...
         }
      }
   }
}

在此案例中,Fakes 會將運行時間實例當做委派的第一個自變數傳遞。

實例方法(單一執行時實例)

實例方法也可以透過使用不同的代理來調整,視呼叫接收端而定。 這種方法允許同一實例方法對該型別的每個實例展現不同的行為。 保留這些 shim 的屬性是 shim 類別本身的實例方法。 每個具現化的襯板類型都會連結到一個襯板類型的原始未經處理的實例。

例如,給定具有實例方法MyClass的類別MyMethod:

// Code under test
public class MyClass {
   public int MyMethod() {
      ...
   }
}

你可以為 MyMethod 建立兩種 shim 類型,讓第一種一律傳回 5,而第二種一律傳回 10:

// Unit test code
var myClass1 = new ShimMyClass()
{
   MyMethod = () => 5
};
var myClass2 = new ShimMyClass { MyMethod = () => 10 };

以下程式碼片段顯示了 ShimMyClass 所產生的型別結構:

// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
   public Func<int> MyMethod {
      set {
         ...
      }
   }
   public MyClass Instance {
      get {
         ...
      }
   }
}

實際的 shimmed 類型實例可透過以下 Instance 屬性存取:

// Unit test code
var shim = new ShimMyClass();
var instance = shim.Instance;

墊片類型也包含隱含的轉換,讓你能直接使用墊片類型:

// Unit test code
var shim = new ShimMyClass();
MyClass instance = shim; // Implicit cast retrieves the runtime instance

瞭解 shim 建構函式

建構函式也不例外,需要進行 shim 處理。 它們可透過 shim 處理,將 shim 類型附加到未來建立的物件上。 例如,每個建構子都以 shim 類型中命名 Constructor 的靜態方法表示。

考慮一個擁有一個構造子且接受整數的類別 MyClass :

public class MyClass {
   public MyClass(int value) {
      this.Value = value;
   }
   ...
}

可將此建構子的 shim 類型設為:無論傳遞給建構子的值為何,之後建立的每個實例在呼叫 Value getter 時都會回傳 -5:

// Unit test code
ShimMyClass.ConstructorInt32 = (@this, value) => {
   var shim = new ShimMyClass(@this) {
      ValueGet = () => -5
   };
};

每種 shim 類型都提供兩種建構函式:

  • 當你需要新實例時,使用預設的建構子。
  • 當您有建構函式 shim 時,請使用接受經 shim 處理的執行個體作為引數的建構函式。
// Unit test code
public ShimMyClass() { }
public ShimMyClass(MyClass instance) : base(instance) { }

以下程式碼說明了 的 ShimMyClass產生型態:

// Fakes generated code
public class ShimMyClass : ShimBase<MyClass>
{
   public static Action<MyClass, int> ConstructorInt32 {
      set {
         ...
      }
   }

   public ShimMyClass() { }
   public ShimMyClass(MyClass instance) : base(instance) { }
   ...
}

存取基底成員

你可以透過為基底類型建立墊片來取得基底成員的墊片屬性。 接著,將子實例傳入基底 shim 類別的建構函式。

例如,以具有實例方法 MyBase 和子型別 MyMethod 的類別 MyChild 為例:

public abstract class MyBase {
   public int MyMethod() {
       ...
   }
}

public class MyChild : MyBase {
}

可以藉由啟動新的 MyBase 接合層來設定 ShimMyBase 的接合層。

// unit test code
var child = new ShimMyChild();
new ShimMyBase(child) { MyMethod = () => 5 };

值得注意的是,當你將子墊片作為參數傳給基礎墊片建構子時,子墊片類型會隱含轉換成子實例。

ShimMyChild 和 ShimMyBase 所產生的型別結構類似下列程式碼:

// Fakes generated code
public class ShimMyChild : ShimBase<MyChild> {
   public ShimMyChild() { }
   public ShimMyChild(Child child)
       : base(child) { }
}
public class ShimMyBase : ShimBase<MyBase> {
   public ShimMyBase(Base target) { }
   public Func<int> MyMethod
   { set { ... } }
}

靜態建構函式

Shim 類型會公開靜態方法 StaticConstructor 來填充類型的靜態建構函式。 由於靜態建構器只會執行一次,你需要確保在存取該類型成員之前,先設定好 shim。

終結器

Fakes 不支援終結者。

私人方法

Fakes 程式碼產生器會為簽章中只有可見類型的私用方法建立 shim 屬性,也就是可見的參數類型和傳回型別。

系結介面

當填充類型實作介面時,程式代碼產生器會發出方法,讓它一次系結來自該介面的所有成員。

例如,假設有一個類別MyClass實作IEnumerable<int>:

public class MyClass : IEnumerable<int> {
   public IEnumerator<int> GetEnumerator() {
       ...
   }
   ...
}

你可以透過呼叫 IEnumerable<int> 方法,為 MyClass 中的 Bind 實作加入 shim:

// Unit test code
var shimMyClass = new ShimMyClass();
shimMyClass.Bind(new List<int> { 1, 2, 3 });

產生的型別結構 ShimMyClass 類似下列程式代碼:

// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
   public ShimMyClass Bind(IEnumerable<int> target) {
       ...
   }
}

更改預設行為

每個產生的 shim 類型都包含 IShimBehavior 介面的實例,可透過 ShimBase<T>.InstanceBehavior 屬性來存取。 每當客戶端呼叫未明確 shimm 的實例成員時,就會觸發此行為。

預設情況下,若未設定特定行為,設計會使用靜態 ShimBehaviors.Current 屬性回傳的實例,通常會 NotImplementedException 拋出例外。

您可以調整任何 "shim" 實例的 InstanceBehavior 屬性,以隨時更改此行為。

例如,你可以變更其行為,使其要麼不執行任何動作,要麼回傳回傳類型的預設值:default(T)

// Unit test code
var shim = new ShimMyClass();

//Return default(T) or do nothing
shim.InstanceBehavior = ShimBehaviors.DefaultValue;

你也可以全域改變所有未明確定義該屬性的 shimmed 實例 InstanceBehavior 的行為,方法是設定 static ShimBehaviors.Current 屬性:

// Unit test code
// Change default shim for all shim instances where the behavior isn't set
ShimBehaviors.Current = ShimBehaviors.DefaultValue;

識別與外部相依性之間的互動

為了協助識別程式碼何時與外部系統或相依項目(統稱為 environment)互動,你可以使用 shims,為某個型別的所有成員(包括靜態方法)指定特定行為。 透過將 shim 類型的靜態 ShimBehaviors.NotImplemented 屬性上的行為設為 Behavior,任何對該類型中未明確設為 shim 的成員所進行的存取,都會擲回 NotImplementedException。 這個結果在測試時可以作為有用的訊號,表示你的程式碼正在嘗試存取外部系統或相依性。

以下是如何在單元測試程式碼中設定這種墊片的範例:

// Unit test code
// Assign the NotImplementedException behavior to ShimMyClass
ShimMyClass.Behavior = ShimBehaviors.NotImplemented;

為了方便起見,也會提供速記方法以達到相同的效果:

// Shorthand to assign the NotImplementedException behavior to ShimMyClass
ShimMyClass.BehaveAsNotImplemented();

從 shim 方法中調用原始方法

在某些情況下,你可能需要在執行墊片方法時同時執行原始方法。 例如,在驗證傳遞至 方法的檔名之後,您可能會想要將文字寫入文件系統。

處理這種情況的一種方法,是使用委派和 ShimsContext.ExecuteWithoutShims() 方法來封裝對原始方法的呼叫:

// Unit test code
ShimFile.WriteAllTextStringString = (fileName, content) => {
  ShimsContext.ExecuteWithoutShims(() => {

     Console.WriteLine("enter");
     File.WriteAllText(fileName, content);
     Console.WriteLine("leave");
  });
};

或者,您可以先將 shim 設為 null、呼叫原始方法,然後再還原 shim:

// Unit test code
ShimsDelegates.Action<string, string> shim = null;

shim = (fileName, content) => {
   try {
      Console.WriteLine("enter");
      // Remove shim in order to call original method
      ShimFile.WriteAllTextStringString = null;
      File.WriteAllText(fileName, content);
   }
   finally
   {
      // Restore shim
      ShimFile.WriteAllTextStringString = shim;
      Console.WriteLine("leave");
   }
};

// Initialize the shim
ShimFile.WriteAllTextStringString = shim;

使用 shim 類型處理並行作業

Shim 類型在 AppDomain 內所有執行緒間運作,且不具備執行緒親和性。 如果你打算使用支援並行的測試執行器,這個特性非常重要。 值得注意的是,涉及 shim 類型的測試無法同時執行,儘管 Fakes 執行時並未強制執行此限制。

使用 Shims 搭配 System.Environment

若要為 System.Environment 類別建立 shim,你需要修改 mscorlib.fakes 檔案。

找到該 \<Assembly> 元素,並在定義後新增以下內容:

<ShimGeneration>
   <Add FullName="System.Environment"/>
</ShimGeneration>

當你做了修改並重建解法後,類別中 System.Environment 的方法和屬性就可以用來做墊片了。

以下是如何將行為指派給 方法的 GetCommandLineArgsGet 範例:

System.Fakes.ShimEnvironment.GetCommandLineArgsGet = ...

當你進行這些修改時,你就能控制並測試程式碼如何與系統環境變數互動,這是全面單元測試的重要工具。