跳過到頁腳內容
.NET幫助

Moq C#(開發者的工作原理)

在軟體開發的世界中,測試是不可或缺的過程。 它確保您的代碼按預期運作,並在它們進入生產之前幫助捕獲錯誤。 測試的一個重要方面是模擬,當談到 C# 測試時,MOQ 是開發人員工具庫中強大的工具。 它提供了對 lambda 表達式的支持。 MOQ,全稱為 .NET 模擬對象框架,簡化了創建單元測試模擬對象的過程。 在本文中,我們將深入探討 C# 中的 MOQ。

什麼是 MOQ?

MOQ - .NET 的模擬框架 是一個為 .NET 應用程序提供的模擬框架,使開發人員能夠快速高效地創建模擬對象。 模擬對象模擬您應用程序中真實對象的行為,使得隔離和測試代碼的特定部分變得更容易。 MOQ 簡化了創建和使用這些模擬對象的過程。

MOQ 的主要特點

  • 流暢接口: MOQ 提供了一個流暢且富有表現力的 API 用於設置期望和驗證。 這使得您的測試代碼更具可讀性且容易理解。
  • 強類型: MOQ 利用 C# 語言特性提供強類型和 IntelliSense 支持,當在定義模擬和期望時。 這減少了測試中運行時錯誤的可能性。
  • 鬆散模擬: MOQ 支持嚴格模擬和鬆散模擬。 鬆散模擬允許您創建對所有方法調用作出響應的模擬對象,而嚴格模擬則強制僅調用預期的方法。
  • 可驗證行為: MOQ 允許您驗證特定方法在您的模擬對象上按預期參數和順序被調用。
  • 回調和返回: 您可以在調用模擬方法時定義回調以執行自定義代碼,並為模擬方法指定返回值。

開始使用 MOQ

在這篇教程中,我們將探討如何使用 MOQ,一個流行的 C# 模擬框架,來促進單元測試。 我們將逐步示範一個簡單的 ATM 交易場景,使用 MOQ 進行依賴項的模擬。

創建一個新的 C# 專案

按照以下步驟來創建一個新的專案:

  1. 打開 Visual Studio,選擇「文件」 > 「新建」 > 「專案...」。
  2. 選擇一個專案模板,配置設置,然後點擊「創建」。

Moq C# (How It Works For Developers) Figure 1 - Create a new console application in Visual Studio 2022

假設您正在為 ATM(自動提款機)開發軟件,並且需要測試身份驗證和提款功能。 ATM 依賴於兩個接口:IHostBankIHSMModule。 我們想要測試代表 ATM 取款功能的 ATMCashWithdrawal 類。

創建兩個接口 IHostBankIHSMModule,它們代表 ATM 系統的依賴項。 定義相關的方法,例如 AuthenticateAmountValidatePIN

// IHostBank.cs
public interface IHostBank
{
    bool AuthenticateAmount(string accountNumber, int amount);
}

// IHSMModule.cs
public interface IHSMModule
{
    bool ValidatePIN(string cardNumber, int pin);
}
// IHostBank.cs
public interface IHostBank
{
    bool AuthenticateAmount(string accountNumber, int amount);
}

// IHSMModule.cs
public interface IHSMModule
{
    bool ValidatePIN(string cardNumber, int pin);
}
' IHostBank.cs
Public Interface IHostBank
	Function AuthenticateAmount(ByVal accountNumber As String, ByVal amount As Integer) As Boolean
End Interface

' IHSMModule.cs
Public Interface IHSMModule
	Function ValidatePIN(ByVal cardNumber As String, ByVal pin As Integer) As Boolean
End Interface
$vbLabelText   $csharpLabel

創建使用上述依賴項執行 ATM 操作的 ATMCashWithdrawal 類。 在這個類中,您將實施一個如 WithdrawAmount 的方法。

// ATMCashWithdrawal.cs
public class ATMCashWithdrawal
{
    private readonly IHSMModule hsmModule;
    private readonly IHostBank hostBank;

    public ATMCashWithdrawal(IHSMModule hsmModule, IHostBank hostBank)
    {
        this.hsmModule = hsmModule;
        this.hostBank = hostBank;
    }

    // Withdraw amount after validating PIN and balance
    public bool WithdrawAmount(string cardNumber, int pin, int amount)
    {
        if (!hsmModule.ValidatePIN(cardNumber, pin))
        {
            return false;
        }

        if (!hostBank.AuthenticateAmount(cardNumber, amount))
        {
            return false;
        }

        // Withdraw the specified amount and perform other operations
        return true;
    }
}
// ATMCashWithdrawal.cs
public class ATMCashWithdrawal
{
    private readonly IHSMModule hsmModule;
    private readonly IHostBank hostBank;

    public ATMCashWithdrawal(IHSMModule hsmModule, IHostBank hostBank)
    {
        this.hsmModule = hsmModule;
        this.hostBank = hostBank;
    }

    // Withdraw amount after validating PIN and balance
    public bool WithdrawAmount(string cardNumber, int pin, int amount)
    {
        if (!hsmModule.ValidatePIN(cardNumber, pin))
        {
            return false;
        }

        if (!hostBank.AuthenticateAmount(cardNumber, amount))
        {
            return false;
        }

        // Withdraw the specified amount and perform other operations
        return true;
    }
}
' ATMCashWithdrawal.cs
Public Class ATMCashWithdrawal
	Private ReadOnly hsmModule As IHSMModule
	Private ReadOnly hostBank As IHostBank

	Public Sub New(ByVal hsmModule As IHSMModule, ByVal hostBank As IHostBank)
		Me.hsmModule = hsmModule
		Me.hostBank = hostBank
	End Sub

	' Withdraw amount after validating PIN and balance
	Public Function WithdrawAmount(ByVal cardNumber As String, ByVal pin As Integer, ByVal amount As Integer) As Boolean
		If Not hsmModule.ValidatePIN(cardNumber, pin) Then
			Return False
		End If

		If Not hostBank.AuthenticateAmount(cardNumber, amount) Then
			Return False
		End If

		' Withdraw the specified amount and perform other operations
		Return True
	End Function
End Class
$vbLabelText   $csharpLabel

創建單元測試專案

現在,讓我們使用 MOQ 為 ATMCashWithdrawal 類創建單元測試來模擬依賴項。

在您的解決方案中創建一個新的單元測試專案,並將其命名為 ATMSystem.Tests

要向 Visual Studio 的解決方案中添加一個 NUnit 測試專案,按照以下步驟:

  1. 右鍵點擊解決方案:在解決方案資源管理器中(通常在右側),右鍵點擊解決方案名稱。
  2. 添加 > 新專案:從上下文菜單中選擇「添加」,然後選擇「新專案...」。
  3. 創建新專案:在「添加新專案」對話框中,您可以搜索「NUnit」以找到可用的 NUnit 模板。 如下圖所示選擇 NUnit 測試專案。

Moq C# (How It Works For Developers) Figure 2 - Add a new NUnit Test Project in your solution.

  1. 配置專案:根據需要配置專案設置,包括專案名稱和位置。
  2. 點擊確定:點擊「創建」或「確定」按鈕將 NUnit 測試專案添加到您的解決方案中。

現在,您擁有一個單獨的 NUnit 測試專案,您可以在其中編寫和管理您的單元測試。 您還可以添加對要測試項目的引用,並在該專案中開始編寫您的 NUnit 測試用例。

要開始在測試專案中使用 MOQ,您需要將 MOQ NuGet 包添加到您的解決方案中。 您可以在 Visual Studio 中使用 NuGet 包管理器來完成此操作,或者在包管理器控制台中運行以下命令:

Install-Package Moq

此命令將安裝該包並添加所有所需的依賴項到專案中。

使用 NUnit 和 MOQ 編寫單元測試來模擬 ATMCashWithdrawal 類的依賴項(IHostBankIHSMModule)。

using Moq;
using NUnit.Framework;

namespace ATMSystem.Tests
{
    public class ATMTests
    {
        private ATMCashWithdrawal atmCash;

        [SetUp]
        public void Setup()
        {
            // Arrange - Setup mock objects
            var hsmModuleMock = new Mock<IHSMModule>();
            hsmModuleMock.Setup(h => h.ValidatePIN("123456781234", 1234)).Returns(true);

            var hostBankMock = new Mock<IHostBank>();
            hostBankMock.Setup(h => h.AuthenticateAmount("123456781234", 500)).Returns(true);

            atmCash = new ATMCashWithdrawal(hsmModuleMock.Object, hostBankMock.Object);
        }

        [Test]
        public void WithdrawAmount_ValidTransaction_ReturnsTrue()
        {
            // Act - Execute the method under test
            bool result = atmCash.WithdrawAmount("123456781234", 1234, 500);

            // Assert - Verify the result
            Assert.IsTrue(result);
        }

        // More test cases for different scenarios (e.g., invalid PIN, insufficient funds)
    }
}
using Moq;
using NUnit.Framework;

namespace ATMSystem.Tests
{
    public class ATMTests
    {
        private ATMCashWithdrawal atmCash;

        [SetUp]
        public void Setup()
        {
            // Arrange - Setup mock objects
            var hsmModuleMock = new Mock<IHSMModule>();
            hsmModuleMock.Setup(h => h.ValidatePIN("123456781234", 1234)).Returns(true);

            var hostBankMock = new Mock<IHostBank>();
            hostBankMock.Setup(h => h.AuthenticateAmount("123456781234", 500)).Returns(true);

            atmCash = new ATMCashWithdrawal(hsmModuleMock.Object, hostBankMock.Object);
        }

        [Test]
        public void WithdrawAmount_ValidTransaction_ReturnsTrue()
        {
            // Act - Execute the method under test
            bool result = atmCash.WithdrawAmount("123456781234", 1234, 500);

            // Assert - Verify the result
            Assert.IsTrue(result);
        }

        // More test cases for different scenarios (e.g., invalid PIN, insufficient funds)
    }
}
Imports Moq
Imports NUnit.Framework

Namespace ATMSystem.Tests
	Public Class ATMTests
		Private atmCash As ATMCashWithdrawal

		<SetUp>
		Public Sub Setup()
			' Arrange - Setup mock objects
			Dim hsmModuleMock = New Mock(Of IHSMModule)()
			hsmModuleMock.Setup(Function(h) h.ValidatePIN("123456781234", 1234)).Returns(True)

			Dim hostBankMock = New Mock(Of IHostBank)()
			hostBankMock.Setup(Function(h) h.AuthenticateAmount("123456781234", 500)).Returns(True)

			atmCash = New ATMCashWithdrawal(hsmModuleMock.Object, hostBankMock.Object)
		End Sub

		<Test>
		Public Sub WithdrawAmount_ValidTransaction_ReturnsTrue()
			' Act - Execute the method under test
			Dim result As Boolean = atmCash.WithdrawAmount("123456781234", 1234, 500)

			' Assert - Verify the result
			Assert.IsTrue(result)
		End Sub

		' More test cases for different scenarios (e.g., invalid PIN, insufficient funds)
	End Class
End Namespace
$vbLabelText   $csharpLabel

在此測試代碼中,我們使用 MOQ 為 IHSMModuleIHostBank 創建模擬對象並指定它們在測試期間調用時的行為。

在上面的代碼示例中,我們展示了使用 MOQ 在 C# 中模擬對象的概念。 我們為 IHSMModuleIHostBank 接口創建模擬對象,模擬它們在單元測試中的行為。 這使我們能夠通過控制這些模擬對象的響應,隔離並徹底測試 ATMCashWithdrawal 類別。 通過模擬,我們可以確保我們的代碼正確地與這些依賴項交互,使得我們的測試專注、可預測,並且能有效地識別特定代碼單元中的問題。 這種做法增強了整體的可靠性、可維護性和測試代碼的質量。

步驟 3 運行測試

  1. 構建您的解決方案以確保一切都是最新的。
  2. 在 Visual Studio 中打開測試資源管理器(測試 > 測試資源管理器)。
  3. 在測試資源管理器中點擊「全部運行」按鈕來執行您的單元測試。
  4. 查看測試結果。 您應該看到您編寫的測試(WithdrawAmount_ValidTransaction_ReturnsTrue)通過。

Moq C# (How It Works For Developers) Figure 3 - To run the Tests, first you will have to build the solution. 在這種方式下,我們可以有效地模擬依賴項,隔離我們想要測試的代碼,並確保它在各種情境下的行為如預期一樣。

這種做法提升了您的軟件的可靠性和可維護性,使得在開發過程中更容易識別和修復問題。 IronPDF 文檔和功能概述 是一個強大的 C# 庫,使得開發人員能夠在其應用程序中處理 PDF 文檔。

介绍 IronPDF

它提供了廣泛的功能,包括從各種來源創建、修改和轉換 PDF 文件,例如 HTML、圖像和現有的 PDF。 當與前面教程中討論的模擬對象概念相結合時,IronPDF 可以成為在單元測試中生成和操作 PDF 文檔的有價值的工具。 IronPDF 的主要功能是它的 HTML 到 PDF 轉換 功能,確保佈局和樣式完好無損。

它將網頁內容轉換為 PDF,非常適合報告、發票和文檔。 例如,如果您有一個涉及 PDF 生成或處理的專案,您可以使用 IronPDF 創建模擬 PDF 文檔來模擬現實情境。 C#雙問號(它對開發者的作用):圖1 - IronPDF網頁

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

這對於測試和驗證您的代碼如何與 PDF 文件交互特別有用。 您可以生成具有特定內容、佈局和屬性的模擬 PDF,然後將其用作測試裝置以確保您的代碼生成了所需的 PDF 輸出或正確處理 PDF 相關操作。 ### 為生成 PDF 創建模擬對象

假設您正在開發一個生成財務報告的應用程序,這些報告需要保存並以 PDF 文檔的形式分發。

在此情況下,您可能希望測試 PDF 生成並確保內容和格式是正確的。 首先,我們需要將 IronPDF 添加到我們的項目中。

在 NuGet 包管理器控制台中輸入以下命令來安裝 IronPDF。 此命令將安裝並添加必要的依賴項到我們的項目中。

Install-Package IronPdf

以下是如何將 IronPDF 結合到單元測試過程中的方法:

生成模擬 PDF

您可以使用 IronPDF 創建具有特定內容和樣式的模擬 PDF 文檔來模擬真實的財務報告。

這些模擬 PDF 可以用作您的單元測試的測試裝置,如以下代碼片段所示: ### 使用模擬 PDF 進行單元測試

public class PDFGenerator
{
    public void GenerateFinancialReport(string reportData)
    {
        var renderer = new ChromePdfRenderer();

        // Generate the report HTML
        string reportHtml = GenerateReportHtml(reportData);
        PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(reportHtml);

        // Save the PDF to a file or memory stream
        pdfDocument.SaveAs("FinancialReport.pdf");
    }

    private string GenerateReportHtml(string reportData)
    {
        // Generate the report HTML based on the provided data
        // (e.g., using Razor views or any HTML templating mechanism)
        // Return the HTML as a string
        return "<h1>my Report</h1>";
    }
}
public class PDFGenerator
{
    public void GenerateFinancialReport(string reportData)
    {
        var renderer = new ChromePdfRenderer();

        // Generate the report HTML
        string reportHtml = GenerateReportHtml(reportData);
        PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(reportHtml);

        // Save the PDF to a file or memory stream
        pdfDocument.SaveAs("FinancialReport.pdf");
    }

    private string GenerateReportHtml(string reportData)
    {
        // Generate the report HTML based on the provided data
        // (e.g., using Razor views or any HTML templating mechanism)
        // Return the HTML as a string
        return "<h1>my Report</h1>";
    }
}
Public Class PDFGenerator
	Public Sub GenerateFinancialReport(ByVal reportData As String)
		Dim renderer = New ChromePdfRenderer()

		' Generate the report HTML
		Dim reportHtml As String = GenerateReportHtml(reportData)
		Dim pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(reportHtml)

		' Save the PDF to a file or memory stream
		pdfDocument.SaveAs("FinancialReport.pdf")
	End Sub

	Private Function GenerateReportHtml(ByVal reportData As String) As String
		' Generate the report HTML based on the provided data
		' (e.g., using Razor views or any HTML templating mechanism)
		' Return the HTML as a string
		Return "<h1>my Report</h1>"
	End Function
End Class
$vbLabelText   $csharpLabel

我們將編寫使用 IronPDF 來生成表示各種報告情境的模擬 PDF 的測試。

然後,我們將我們的代碼生成的實際 PDF 與這些模擬 PDF 進行比較,以確保內容、格式和結構如預期一樣。 在此測試代碼中,我們生成了一個代表預期輸出的模擬 PDF (expectedPdf)並與 PDFGenerator 生成的 PDF (actualPdf)進行比較。

using IronPdf;
using NUnit.Framework;

internal class PDFGeneratorTests
{
    [Test]
    public void GenerateFinancialReport_CreatesCorrectPDF()
    {
        // Arrange
        var pdfGenerator = new PDFGenerator();
        var expectedPdf = PdfDocument.FromFile("ExpectedFinancialReport.pdf"); // Load a mock PDF

        // Act
        pdfGenerator.GenerateFinancialReport("Sample report data");
        var actualPdf = PdfDocument.FromFile("FinancialReport.pdf");

        // Assert
        Assert.AreEqual(actualPdf.ExtractAllText(), expectedPdf.ExtractAllText());
    }
}
using IronPdf;
using NUnit.Framework;

internal class PDFGeneratorTests
{
    [Test]
    public void GenerateFinancialReport_CreatesCorrectPDF()
    {
        // Arrange
        var pdfGenerator = new PDFGenerator();
        var expectedPdf = PdfDocument.FromFile("ExpectedFinancialReport.pdf"); // Load a mock PDF

        // Act
        pdfGenerator.GenerateFinancialReport("Sample report data");
        var actualPdf = PdfDocument.FromFile("FinancialReport.pdf");

        // Assert
        Assert.AreEqual(actualPdf.ExtractAllText(), expectedPdf.ExtractAllText());
    }
}
Imports IronPdf
Imports NUnit.Framework

Friend Class PDFGeneratorTests
	<Test>
	Public Sub GenerateFinancialReport_CreatesCorrectPDF()
		' Arrange
		Dim pdfGenerator As New PDFGenerator()
		Dim expectedPdf = PdfDocument.FromFile("ExpectedFinancialReport.pdf") ' Load a mock PDF

		' Act
		pdfGenerator.GenerateFinancialReport("Sample report data")
		Dim actualPdf = PdfDocument.FromFile("FinancialReport.pdf")

		' Assert
		Assert.AreEqual(actualPdf.ExtractAllText(), expectedPdf.ExtractAllText())
	End Sub
End Class
$vbLabelText   $csharpLabel

我們提取了兩個 PDF 的內容以驗證它們是否具有相同的內容。 總之,將 MOQ 與 IronPDF 結合到我們的單元測試過程中,使我們可以全面驗證我們軟件應用程序的行為。

結論

MOQ 使我們能夠隔離特定的代碼組件,控制依賴項,並模擬複雜的場景,使得我們能編寫專注且可靠的測試。 同時,IronPDF 通過促進 PDF 文檔的生成和操作來增強我們的測試能力,確保我們的 PDF 相關功能得到徹底檢查。

通過將這些工具集成到我們的測試工具箱中,我們可以自信地開發出滿足功能和性能要求的強大而高質量的軟件。 這種強大的單元測試與 MOQ 結合和 PDF 驗證與 IronPDF 結合顯著提高了我們應用程序的整體質量和可靠性。 值得注意的是,IronPDF 提供了一個 免費試用版 來測試其功能。

如果您覺得它滿足您的需求,您可以選擇購買 商業許可證,這樣您就可以在專案中繼續使用 IronPDF 的功能,充分利用已授權版本帶來的所有優勢和支援,確保 PDF 相關功能的流暢集成。 If you find it suits your needs, you have the option to purchase a commercial license which allows you to continue using IronPDF's capabilities in your projects with the full advantage and support that come with a licensed version, ensuring the smooth integration of PDF-related functionalities into your applications.

常見問題解答

Moq 如何增強 C# 中的單元測試?

Moq 增強 C# 中的單元測試,允許開發人員創建模擬對象,這些對象模擬真實對象的行為。這有助於隔離開發人員希望測試的特定代碼組件,確保更準確和專注的測試結果。

Moq 的主要功能是什麼?

Moq 提供設置期望的流暢介面,強類型可減少運行時錯誤,並支持嚴格和寬鬆的模擬,使其成為 C# 應用中的一個有效的單元測試工具。

如何將 IronPDF 集成到 C# 項目中以生成 PDF?

要將 IronPDF 集成到 C# 項目中,可以使用 NuGet 套件管理器控制台並運行命令 Install-Package IronPdf。這將添加生成和操作 PDF 所需的依賴項。

在單元測試中使用模擬 PDF 的目的何在?

模擬 PDF 在單元測試中用於模擬涉及 PDF 文件的真實場景。這允許開發人員測試 PDF 生成和操作功能,確保他們的應用正確處理 PDF。

IronPDF 可以用於商業應用程序嗎?

是的,IronPDF 提供商業許可選項,允許開發人員在商業應用中使用其全方位的 PDF 功能,由許可版本提供的支持和能力。

如何在單元測試中同時使用 Moq 和 IronPDF?

Moq 可以用於模擬代碼中的依賴項,而 IronPDF 可以用於生成和操作 PDF。它們結合使用能夠讓開發人員編寫可靠的測試,確保代碼邏輯和與 PDF 相關的功能的質量。

Moq 在測試 C# 中的依賴交互中起什麼作用?

Moq 幫助測試依賴交互,允許開發人員創建接口的模擬實現,例如 `IHostBank` 和 `IHSMModule`。這允許您模擬各種場景並驗證代碼如預期地與依賴交互。

Moq 如何處理嚴格驗證和寬鬆驗證?

Moq 支持嚴格驗證和寬鬆驗證。嚴格驗證要求滿足所有期望,對於精確測試非常有用。寬鬆驗證則更靈活,允許只驗證感興趣的交互,在複雜系統中很有幫助。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。