跳過到頁腳內容
.NET幫助

C# 單元測試(對於開發者的運行原理)

Introduction to Unit Testing in C#

單元測試是軟體開發的關鍵階段,可協助開發人員驗證原始程式碼個別單元的功能。 在 C# 中,單元測試可確保每個元件或方法在各種條件下正確運作。 透過隔離程式的每個部分並顯示個別部分沒有錯誤,單元測試對應用程式的可靠性貢獻良多。 在本文中,我們將探討 C# 單元測試專案和 IronPDF library 適用於 .NET 的基本知識。

在 Visual Studio 中設定您的第一個單元測試。

建立單元測試專案

要開始使用 C# 進行單元測試,您需要在 Visual Studio 中設定其中一個單元測試專案。 Visual Studio 提供內建的單元測試框架,讓您可以直接開始。 建立新專案時,請選擇 C# 類別下的"單元測試專案"範本。 本範本設定了建立單元測試並有效執行所需的一切。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Unit_Test_Project_Example
{
    // A simple calculator class with an Add method
    public class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    // A test class to validate the functionality of the Calculator class
    [TestClass]
    public class CalculatorTests
    {
        // A test method to check if the Add method in Calculator returns the correct sum
        [TestMethod]
        public void Add_ShouldReturnCorrectSum()
        {
            // Arrange
            var calculator = new Calculator();

            // Act
            var result = calculator.Add(2, 2);

            // Assert
            Assert.AreEqual(4, result);
        }
    }
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Unit_Test_Project_Example
{
    // A simple calculator class with an Add method
    public class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    // A test class to validate the functionality of the Calculator class
    [TestClass]
    public class CalculatorTests
    {
        // A test method to check if the Add method in Calculator returns the correct sum
        [TestMethod]
        public void Add_ShouldReturnCorrectSum()
        {
            // Arrange
            var calculator = new Calculator();

            // Act
            var result = calculator.Add(2, 2);

            // Assert
            Assert.AreEqual(4, result);
        }
    }
}
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports System

Namespace Unit_Test_Project_Example
	' A simple calculator class with an Add method
	Public Class Calculator
		Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
			Return a + b
		End Function
	End Class

	' A test class to validate the functionality of the Calculator class
	<TestClass>
	Public Class CalculatorTests
		' A test method to check if the Add method in Calculator returns the correct sum
		<TestMethod>
		Public Sub Add_ShouldReturnCorrectSum()
			' Arrange
			Dim calculator As New Calculator()

			' Act
			Dim result = calculator.Add(2, 2)

			' Assert
			Assert.AreEqual(4, result)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

瞭解測試方法與測試類

在單元測試專案中,您將測試組織成類和方法。 測試類代表應一起執行的單元測試方法的集合。 每個使用 [TestMethod] 屬性裝飾的單元測試方法,都包含測試程式碼特定功能的邏輯。 測試類別本身會以 [TestClass] 屬性標記,向測試框架示意它包含要執行的測試。

執行並瞭解您的測試。

在 Visual Studio 中使用測試總管。

Visual Studio Test Explorer 視窗是您執行和管理所有測試方法的中樞。 您可以執行所有測試、部分測試或單獨測試。 執行測試後,Test Explorer 會提供通過與失敗測試的詳細摘要,讓您快速找出並處理問題。

解讀測試結果

*通過測試:*這些測試運行成功,表示被測程式碼在指定條件下如預期運行。 測試失敗:**這表示預期結果與實際結果之間存在差異,表示需求或測試程式碼中可能存在錯誤或誤解。

及時調查失敗的測試是非常重要的,因為它們可以提供程式碼中問題的早期警示訊號。

C# Unit Testing (How It Works For Developers):圖 1 - 在 Visual Studio 中通過單元測試的範例

撰寫 C# 單元測試的進階技術與最佳實務

除了撰寫和執行測試之外,掌握 C# 的單元測試還需瞭解一些進階技術和最佳實務。 這些方法可協助您撰寫更有效率、更有效的測試,確保您的應用程式可靠且可維護。

有效組織測試

良好的組織是維護大型測試套件的關鍵。 將您的測試依其涵蓋的功能邏輯地分類。 使用描述性的名稱來命名您的測試方法和類別,以指出每個測試所要驗證的內容。 這種方法可以讓您日後更容易找到並理解測試,尤其是當您的測試套件不斷增加時。

Mocking 和依賴注入。

通常,您要測試的程式碼會與外部資源或應用程式的其他部分互動。 在這種情況下,請使用 Moq 或 NSubstitute 等模擬框架來建立模擬物件。 這些替身模仿真實物件的行為,讓您可以隔離測試您的程式碼。 依賴注入可讓您的程式碼更具可測性,因為它允許您在測試時以模擬或存根取代真正的依賴。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

// A sample test class demonstrating the use of mocks
[TestClass]
public class ProductServiceTests
{
    // A test method to verify the GetProductById method of ProductService
    [TestMethod]
    public void GetProductById_ShouldReturnCorrectProduct()
    {
        // Arrange
        var mockRepository = new Mock<IProductRepository>();
        mockRepository.Setup(x => x.FindById(1)).Returns(new Product { Id = 1, Name = "Laptop" });

        ProductService productService = new ProductService(mockRepository.Object);

        // Act
        Product result = productService.GetProductById(1);

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual("Laptop", result.Name);
    }
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

// A sample test class demonstrating the use of mocks
[TestClass]
public class ProductServiceTests
{
    // A test method to verify the GetProductById method of ProductService
    [TestMethod]
    public void GetProductById_ShouldReturnCorrectProduct()
    {
        // Arrange
        var mockRepository = new Mock<IProductRepository>();
        mockRepository.Setup(x => x.FindById(1)).Returns(new Product { Id = 1, Name = "Laptop" });

        ProductService productService = new ProductService(mockRepository.Object);

        // Act
        Product result = productService.GetProductById(1);

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual("Laptop", result.Name);
    }
}
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Moq

' A sample test class demonstrating the use of mocks
<TestClass>
Public Class ProductServiceTests
	' A test method to verify the GetProductById method of ProductService
	<TestMethod>
	Public Sub GetProductById_ShouldReturnCorrectProduct()
		' Arrange
		Dim mockRepository = New Mock(Of IProductRepository)()
		mockRepository.Setup(Function(x) x.FindById(1)).Returns(New Product With {
			.Id = 1,
			.Name = "Laptop"
		})

		Dim productService As New ProductService(mockRepository.Object)

		' Act
		Dim result As Product = productService.GetProductById(1)

		' Assert
		Assert.IsNotNull(result)
		Assert.AreEqual("Laptop", result.Name)
	End Sub
End Class
$vbLabelText   $csharpLabel

使用資料驅動的測試

資料驅動測試可讓您以不同的輸入資料多次執行相同的測試方法。 此技術特別適用於測試廣泛的輸入和情境,而無需撰寫多種測試方法。 Visual Studio 支援資料驅動測試,讓您可以從各種來源指定測試資料,例如內嵌資料、CSV 檔案或資料庫。

瞭解並有效使用 Asserts

Assert 是您測試方法的核心,因為它們會驗證您的測試結果。 瞭解測試框架中可用的 assert 方法範圍,並適當使用這些方法來檢查預期值、異常或條件。 使用正確的斷言可以讓您的測試更清楚、更穩健。

持續整合與測試自動化

將單元測試整合至持續整合 (CI) 管道。這可確保每次對程式碼進行變更時,測試都會自動執行,有助於及早發現並修復問題。 自動化也有助於頻繁一致地執行測試,這對於維護健康的程式碼庫至關重要。

保持測試與生產程式碼同步

您的單元測試只有在與生產程式碼一致的情況下才是最好的。 確保功能上的任何變更都能反映在相對應的單元測試中。 此做法可避免過時的測試不正確地通過,並確保您的測試套件準確地代表應用程式的狀態。

從失敗的測試中學習

測試失敗時,是學習和改進的機會。 失敗的測試可能會揭露您的程式碼中意想不到的行為、不正確的假設,或是比必要更複雜、更容易出錯的地方。 仔細分析失敗的測試以瞭解其根本原因,並利用這些洞察力來強化您的測試和生產程式碼。

IronPDF 簡介

C# Unit Testing (How It Works For Developers):圖 2 - IronPDF 網站

IronPDF 適用於 .NET PDF Development 是專為 .NET 開發人員設計的綜合資料庫,可讓他們在應用程式中產生、處理和讀取 PDF 文件。 IronPDF 因其能夠直接從 HTML、CSS、圖片和 JavaScript 產生 PDF 而聞名,從而建立出最佳的 PDF。 它支援廣泛的 .NET 專案類型和應用環境,包括網頁和桌面應用程式、服務等,跨越 Windows、Linux 和 macOS 等各種作業系統,以及 Docker 和 Azure、AWS 等雲端環境。

IronPDF 可輕鬆地將 HTML、URL 和整個網頁轉換成外觀與原始碼一樣的專業 PDF。 非常適合報告、發票或網路內容的歸檔。 如果您正在尋找一種簡單的方式將 HTML 轉換為 PDF,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

程式碼範例

以下是在 C# 單元測試情境中使用 IronPDF 的範例。 假設您想要測試一個從 HTML 內容產生 PDF 的函式。 您可以使用 IronPDF 將 HTML 呈現為 PDF,然後驗證 PDF 的存在或內容,作為測試的一部分:

using IronPdf;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;

// A sample test class to verify PDF generation
[TestClass]
public class PdfGenerationTests
{
    // A test method to verify HTML to PDF generation using IronPDF
    [TestMethod]
    public void TestHtmlToPdfGeneration()
    {
        IronPdf.License.LicenseKey = "License-Key"; // Set your IronPDF license key

        var renderer = new ChromePdfRenderer();

        // Render HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, world!</h1>");

        string filePath = Path.Combine(Path.GetTempPath(), "test.pdf");

        // Save the generated PDF to a file
        pdf.SaveAs(filePath);

        // Assert the PDF file was created successfully
        Assert.IsTrue(File.Exists(filePath), "The generated PDF does not exist.");

        // Additional assertions to verify the PDF content could be added here
        // Clean up generated file
        File.Delete(filePath);
    }
}
using IronPdf;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;

// A sample test class to verify PDF generation
[TestClass]
public class PdfGenerationTests
{
    // A test method to verify HTML to PDF generation using IronPDF
    [TestMethod]
    public void TestHtmlToPdfGeneration()
    {
        IronPdf.License.LicenseKey = "License-Key"; // Set your IronPDF license key

        var renderer = new ChromePdfRenderer();

        // Render HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, world!</h1>");

        string filePath = Path.Combine(Path.GetTempPath(), "test.pdf");

        // Save the generated PDF to a file
        pdf.SaveAs(filePath);

        // Assert the PDF file was created successfully
        Assert.IsTrue(File.Exists(filePath), "The generated PDF does not exist.");

        // Additional assertions to verify the PDF content could be added here
        // Clean up generated file
        File.Delete(filePath);
    }
}
Imports IronPdf
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports System
Imports System.IO

' A sample test class to verify PDF generation
<TestClass>
Public Class PdfGenerationTests
	' A test method to verify HTML to PDF generation using IronPDF
	<TestMethod>
	Public Sub TestHtmlToPdfGeneration()
		IronPdf.License.LicenseKey = "License-Key" ' Set your IronPDF license key

		Dim renderer = New ChromePdfRenderer()

		' Render HTML to a PDF
		Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, world!</h1>")

		Dim filePath As String = Path.Combine(Path.GetTempPath(), "test.pdf")

		' Save the generated PDF to a file
		pdf.SaveAs(filePath)

		' Assert the PDF file was created successfully
		Assert.IsTrue(File.Exists(filePath), "The generated PDF does not exist.")

		' Additional assertions to verify the PDF content could be added here
		' Clean up generated file
		File.Delete(filePath)
	End Sub
End Class
$vbLabelText   $csharpLabel

本範例示範了一個簡單的單元測試,使用 IronPDF 從 HTML 字串產生 PDF、儲存至暫存檔案,然後驗證檔案是否存在。

C# Unit Testing (How It Works For Developers):圖 3 - 前一個測試已通過

結論

C# Unit Testing (How It Works For Developers):圖 4 - IronPDF 授權頁面

單元測試是軟體開發生命週期中不可或缺的一環。 透過設定與撰寫有效的測試、透過 Visual Studio 的 Test Explorer 執行測試,以及使用程式碼涵蓋率工具,可確保 C# 應用程式的可靠性,並維持高品質的標準。 透過了解並應用測試驅動的開發原則,您可以進一步提升 C# 單元測試專案的品質。 請記住,單元測試的目的不只是找出錯誤,而是為您的應用程式建立穩健的基礎,以利於更新、除錯和新增功能。 探索 IronPDF 許可選項,許可選項從 $$ liteLicense 開始。

常見問題解答

單元測試在 C# 開發中的重要性是什麼?

單元測試在 C# 開發中至關重要,因為它確保每個代碼單元都能正常運行,有助於整體軟件的可靠性。通過隔離組件並驗證其行為,單元測試幫助開發人員及早發現錯誤並保持高質量的代碼。

如何在 Visual Studio 中為 C# 創建單元測試項目?

要在 Visual Studio 中創建單元測試項目,設置新項目時從 C# 類別中選擇“單元測試項目”模板。這提供了開發和有效執行單元測試所需的結構和工具。

如何在 C# 中將 HTML 內容轉換為 PDF 用於測試用途?

您可以使用 IronPDF 庫將 HTML 內容轉換為 C# 中的 PDF。這涉及將 HTML 呈現為 PDF 並通過單元測試驗證其輸出,確保轉換過程在您的應用中如預期工作。

在單元測試中使用 IronPDF 有哪些好處?

IronPDF 通過允許開發人員在 .NET 應用中生成和操作 PDF 文檔來增強單元測試。這種集成支持涉及 PDF 生成的測試場景,確保文檔被準確生成和格式化。

模擬對象如何增強 C# 中的單元測試?

模擬對象模擬實際對象以隔離待測代碼,使您能夠專注於特定功能。這對於測試與外部系統或其他應用組件的交互特別有用。

編寫 C# 單元測試的其中一些高級技術是什麼?

高級技術包括使用模擬框架、依賴注入和數據驅動測試來創建有效且可維護的測試。這些方法有助於測試範圍廣泛的場景,並確保隨著代碼的發展測試保持相關性。

持續集成如何改善 C# 單元測試?

持續集成 (CI) 通過在代碼更改時自動執行測試來改善 C# 單元測試。這可確保迅速發現和解決任何問題,從而維護代碼質量並促進穩定的開發過程。

斷言在 C# 單元測試中為什麼重要?

斷言很重要,因為它們驗證測試的預期結果。通過確保代碼按預期行為運行,斷言確認被測功能的正確性,從而提高應用的可靠性。

測試瀏覽器在 Visual Studio 中的角色是什麼?

Visual Studio 中的測試瀏覽器是一個允許開發人員運行和管理單元測試的工具。它提供了一個用戶友好的接口來執行所有測試、特定測試組或個別測試,並顯示結果摘要,指出哪些測試通過或失敗。

如何在 C# 中進行數據驅動測試?

C# 中的數據驅動測試涉及以不同的輸入數據多次運行同一測試。這可以通過使用各種數據源(如內聯數據、CSV 文件或數據庫)實現,允許在不同場景下進行全面測試。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我