跳至頁尾內容
.NET 幫助

AutoFixture C#(開發者使用方法)

AutoFixture 是適用於 .NET 的開放源碼函式庫,目的在於最小化單元測試撰寫中的"安排"階段,進而改善測試管理。 其主要目的是讓開發人員能夠專注於他們正在測試的內容,而非設定過程,方法是讓您使用測試資料建立物件圖形。 本文將探討 AutoFixture 如何透過有效率的測試資料產生,來促進測試驅動的開發。

AutoFixture 是 C# 中一個功能強大的函式庫,旨在簡化為單元測試建立測試資料的流程。 它透過自動產生測試案例的資料,協助開發人員避免撰寫重複的設定程式碼。 在單元測試中,AutoFixture 提供了簡化的方式來產生測試資料,確保每個單元測試都能在多樣且真實的輸入下執行。 AutoFixture 可自動產生測試資料,減少手動設定的需求,讓 C# 測試更有效率。

AutoFixture C# (How It Works For Developers):圖 1 - AutoFixture

安裝與設定 AutoFixture

AutoFixture 以 NuGet 套件的形式提供,可使用 NuGet Package Manager Console 或 Visual Studio 的 NuGet Package Manager UI 中的 .NET add 套件進行安裝。

Install-Package AutoFixture

NuGet 將下載並安裝最新版本的 AutoFixture 及其相依性到您的專案中。

為類建立測試資料的範例

假設我們有一個簡單的 Employee 類別,其中具有 FirstName, LastNameAge 等屬性。 與其在單元測試中手動建立這個類別的實體,我們可以利用 AutoFixture 來為我們產生隨機資料。

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public Employee(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }

    public string GetFullName() => $"{FirstName} {LastName}";
}
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public Employee(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }

    public string GetFullName() => $"{FirstName} {LastName}";
}
$vbLabelText   $csharpLabel

程式碼描述

Employee 類封裝員工的基本詳細資訊,包括他們的名字、姓氏和年齡,分別由屬性 FirstName, LastNameAge 表示。 其建構器會接受這些詳細資訊作為參數,並將其指定給相關的屬性,以利於員工物件的實體化。 此外,GetFullName 方法會連結員工的名和姓,以字串形式傳回全名。

為我們的測試情境設定程式碼

接下來,我們將建立一個測試類別,以測試 Employee 類別:

using AutoFixture;

public class EmployeeTests
{
    private readonly IFixture _fixture;

    public EmployeeTests()
    {
        // Using AutoFixture's Fixture to create test data
        _fixture = new Fixture();
    }
}
using AutoFixture;

public class EmployeeTests
{
    private readonly IFixture _fixture;

    public EmployeeTests()
    {
        // Using AutoFixture's Fixture to create test data
        _fixture = new Fixture();
    }
}
$vbLabelText   $csharpLabel

程式碼描述

此程式碼片段將 AutoFixture 納入 Employee 類的單元測試中。 透過匯入 AutoFixture 命名空間,開發人員可以存取資料產生功能。 _fixture 欄位以 Fixture 的新實例初始化,可簡化測試資料的建立。 此設定可增強測試效率與可靠性,以達到全面的 Employee 類別涵蓋範圍。

範例 1:驗證員工測試案例物件值

[Fact]
public void Employee_ShouldHaveValidValues()
{
    // Arrange
    var firstName = _fixture.Create<string>();
    var lastName = _fixture.Create<string>();
    var age = _fixture.Create<int>();

    // Act
    var employee = new Employee(firstName, lastName, age);

    // Assert
    Assert.Equal(firstName, employee.FirstName);
    Assert.Equal(lastName, employee.LastName);
    Assert.Equal(age, employee.Age);
}
[Fact]
public void Employee_ShouldHaveValidValues()
{
    // Arrange
    var firstName = _fixture.Create<string>();
    var lastName = _fixture.Create<string>();
    var age = _fixture.Create<int>();

    // Act
    var employee = new Employee(firstName, lastName, age);

    // Assert
    Assert.Equal(firstName, employee.FirstName);
    Assert.Equal(lastName, employee.LastName);
    Assert.Equal(age, employee.Age);
}
$vbLabelText   $csharpLabel

程式碼描述

測試方法 Employee_ShouldHaveValidValues 驗證 Employee 類是否正確地以提供的值初始化其屬性。 使用測試治具為 FirstName, LastName, 和 Age 產生隨機資料,測試建立一個 Employee 實例。 然後,它斷言 Employee 物件的 FirstName, LastNameAge 屬性與產生的值相符,以確保建構器能準確地設定這些屬性。

範例 2:當啟用建構器時驗證 Employee

[Fact]
public void CreateEmployee_ValidData_ReturnsEmployeeObject()
{
    // Arrange
    var employee = _fixture.Create<Employee>();

    // Act 
    // Assert
    Assert.NotNull(employee);
    Assert.False(string.IsNullOrEmpty(employee.FirstName));
    Assert.NotNull(employee.LastName);
    Assert.True(employee.Age > 0);
}
[Fact]
public void CreateEmployee_ValidData_ReturnsEmployeeObject()
{
    // Arrange
    var employee = _fixture.Create<Employee>();

    // Act 
    // Assert
    Assert.NotNull(employee);
    Assert.False(string.IsNullOrEmpty(employee.FirstName));
    Assert.NotNull(employee.LastName);
    Assert.True(employee.Age > 0);
}
$vbLabelText   $csharpLabel

程式碼描述

此測試方法包含驗證 Employee 物件的屬性是否與隨機產生的值相符的測試斷言。 它會驗證 String 類型的屬性 FirstNameLastName 以及 int Age 是否正確設定且有效。 任何失敗的斷言都表示為員工詳細資料所產生的預期值與隨機值不匹配。

AutoFixture C# (How It Works For Developers):圖 2 - 有效的員工資料單元測試

介紹 IronPDF。

IronPDF C# PDF Library 是 Iron Software 開發的強大 C# PDF 函式庫,可方便 PDF 文字的讀取使用 HTML 建立 PDF 文件。 此多功能工具可將包含樣式資訊的簡易格式化文件轉換為高品質的 PDF。 有了 IronPDF,從 HTML 文檔生成 PDF 是一個無縫的過程,使用者可以從 URL 擷取 HTML 內容,並將其轉換成結構良好的 PDF 檔案。 這項功能讓 IronPDF 成為希望直接從網頁內容自動化、簡化專業 PDF 文件製作的開發者必備工具。

AutoFixture C# (How It Works For Developers):圖 3 - IronPdf

安裝 IronPDF。

開啟 NuGet Package Manager 主控台,並執行下列指令:

Install-Package IronPdf

使用 IronPdf 的 AutoFixture 功能的程式碼範例

以下是一個範例,展示如何在 IronPDF 旁邊使用 AutoFixture 來產生 PDF 的員工資料:

using DemoAutofixture;
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class EmployeePdfGenerator
{
    private readonly Fixture _fixture;

    public EmployeePdfGenerator()
    {
        _fixture = new Fixture();
    }

    public List<Employee> GenerateEmployees(int count)
    {
        return _fixture.CreateMany<Employee>(count).ToList();
    }

    public void GeneratePdf(List<Employee> employees, string filePath)
    {
        IronPdf.License.LicenseKey = "Your-License-Key-Here";
        var renderer = new ChromePdfRenderer();
        string htmlContent = GenerateHtml(employees);

        try
        {
            renderer.RenderHtmlAsPdf(htmlContent).SaveAs(filePath);
            Console.WriteLine("PDF Created Successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error generating PDF: {ex.Message}");
        }
    }

    private string GenerateHtml(List<Employee> employees)
    {
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<!DOCTYPE html><html><head><title>Employee List</title></head><body><h1>Employee List</h1><ul>");

        foreach (var employee in employees)
        {
            htmlBuilder.Append($"<li>{employee.GetFullName()} - Age: {employee.Age}</li>");
        }

        htmlBuilder.Append("</ul></body></html>");
        return htmlBuilder.ToString();
    }
}
using DemoAutofixture;
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class EmployeePdfGenerator
{
    private readonly Fixture _fixture;

    public EmployeePdfGenerator()
    {
        _fixture = new Fixture();
    }

    public List<Employee> GenerateEmployees(int count)
    {
        return _fixture.CreateMany<Employee>(count).ToList();
    }

    public void GeneratePdf(List<Employee> employees, string filePath)
    {
        IronPdf.License.LicenseKey = "Your-License-Key-Here";
        var renderer = new ChromePdfRenderer();
        string htmlContent = GenerateHtml(employees);

        try
        {
            renderer.RenderHtmlAsPdf(htmlContent).SaveAs(filePath);
            Console.WriteLine("PDF Created Successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error generating PDF: {ex.Message}");
        }
    }

    private string GenerateHtml(List<Employee> employees)
    {
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<!DOCTYPE html><html><head><title>Employee List</title></head><body><h1>Employee List</h1><ul>");

        foreach (var employee in employees)
        {
            htmlBuilder.Append($"<li>{employee.GetFullName()} - Age: {employee.Age}</li>");
        }

        htmlBuilder.Append("</ul></body></html>");
        return htmlBuilder.ToString();
    }
}
$vbLabelText   $csharpLabel

若要使用這個類別,您可以實體化 EmployeePdfGenerator ,產生一個員工清單,然後呼喚 GeneratePdf

List<Employee> employees = new()
{
    new Employee("John", "Smith", 32),
    new Employee("Emily", "Davis", 18),
    new Employee("David", "Brown", 24),
    new Employee("Jane", "Doe", 16),
    new Employee("Michael", "Johnson", 49),
};

EmployeePdfGenerator pdfGenerator = new();
pdfGenerator.GeneratePdf(employees, "EmployeeList.pdf");
List<Employee> employees = new()
{
    new Employee("John", "Smith", 32),
    new Employee("Emily", "Davis", 18),
    new Employee("David", "Brown", 24),
    new Employee("Jane", "Doe", 16),
    new Employee("Michael", "Johnson", 49),
};

EmployeePdfGenerator pdfGenerator = new();
pdfGenerator.GeneratePdf(employees, "EmployeeList.pdf");
$vbLabelText   $csharpLabel

AutoFixture C# (How It Works For Developers):圖 4 - IronPDF 輸出的 Autofixture

程式碼描述

所提供的 C# 程式碼使用 IronPDF 函式庫來產生 PDF 文件,列出員工及其年齡。 它定義了一個 EmployeePdfGenerator 類,該類包含 GeneratePdf 方法,該方法接收 Employee 物件清單和檔案路徑。 在內部,它透過 GenerateHtml 方法建構 HTML 內容,然後再使用 IronPDF 的 HtmlToPdf 類將 HTML 呈現為 PDF,並儲存於指定的檔案路徑。 增強功能包括使用 StringBuilder 來產生 HTML,以及新增 PDF 產生與檔案儲存的基本錯誤處理。

撰寫測試方法

在下面的設定中,AutoFixture 被用來建立 Employee 類的實體,以產生隨機測試資料。 採用 IronPDF 將 HTML 內容(包括員工資訊)無縫轉換成 PDF 格式。 EmployeePdfGenerator 類會協調這些流程,有效地管理資料產生和 PDF 轉換。 與此同時,EmployeePdfGeneratorTests XUnit 測試類可透過嚴格的測試確保 PDF 生成的正常功能。 這種整合式的方法簡化了員工資料的產生與記錄,確保 PDF 產生過程的穩健性與可靠性。

using System.IO;
using Xunit;

public class EmployeePdfGeneratorTests
{
    [Fact]
    public void GeneratePdf_GeneratesPdfFile()
    {
        // Arrange
        var generator = new EmployeePdfGenerator();
        var employees = generator.GenerateEmployees(5);
        string filePath = "EmployeeList.pdf";

        // Act
        generator.GeneratePdf(employees, filePath);

        // Assert
        Assert.True(File.Exists(filePath));
    }
}
using System.IO;
using Xunit;

public class EmployeePdfGeneratorTests
{
    [Fact]
    public void GeneratePdf_GeneratesPdfFile()
    {
        // Arrange
        var generator = new EmployeePdfGenerator();
        var employees = generator.GenerateEmployees(5);
        string filePath = "EmployeeList.pdf";

        // Act
        generator.GeneratePdf(employees, filePath);

        // Assert
        Assert.True(File.Exists(filePath));
    }
}
$vbLabelText   $csharpLabel

這裡的 EmployeePdfGeneratorTests 類包含一個測試案例,可驗證在指定的檔案路徑建立 PDF 檔案,確保 GeneratePdf 方法的功能正確。

AutoFixture C# (How It Works For Developers):圖 5 - AutoFixture C#

結論

AutoFixture 簡化了在 .NET 中撰寫單元測試的"安排"階段,提供開發人員專注於測試案例而非複雜設定的方法。 它簡化了單元測試流程,透過自動產生測試資料,確保多樣且真實的輸入。 結合 IronPDF授權資訊,可提供持續使用與支援的強大組合。

常見問題解答

如何使用AutoFixture在C#中產生測試資料?

您可以使用 AutoFixture 透過其「Fixture」類別在 C# 中產生測試資料。該類別可讓您自動建立包含隨機資料的類別實例,從而可以有效地設定各種測試場景。

在.NET專案中安裝AutoFixture的步驟是什麼?

若要在 .NET 專案中安裝 AutoFixture,可以使用 NuGet 套件管理器控制台,並執行指令Install-Package AutoFixture 。也可以透過 Visual Studio 的 NuGet 套件管理器 UI 進行安裝,在該 UI 中搜尋 AutoFixture 並將其新增至專案。

AutoFixture 如何改善單元測試流程?

AutoFixture 透過自動產生真實且多樣化的測試資料來增強單元測試流程。這減少了手動設定的需求,並確保測試在廣泛的輸入範圍內進行,從而提高測試覆蓋率和可靠性。

AutoFixture 能否與 .NET 中的 PDF 生成庫整合?

是的,AutoFixture 可以與 .NET 中的 IronPDF 等 PDF 生成庫整合。透過使用 AutoFixture 產生數據,您可以利用 IronPDF 的 HTML 轉 PDF 功能,建立包含動態內容(例如員工資料)的 PDF 檔案。

AutoFixture 中的「Fixture」類別有什麼用途?

AutoFixture 中的「Fixture」類別旨在透過自動建立測試資料來簡化測試設定。它會產生包含隨機資料的類別實例,使開發人員能夠更專注於測試邏輯,而不是手動設定資料。

AutoFixture 如何促進測試驅動開發 (TDD)?

AutoFixture 透過提供一種簡單的測試資料產生方式來輔助測試驅動開發 (TDD),使開發人員能夠編寫測試並實現功能,而無需在資料準備上花費過多時間。這簡化了 TDD 流程,使其更有效率。

如何使用 AutoFixture 和 PDF 庫在 C# 中自動建立文件?

您可以使用 C# 結合 AutoFixture 和 IronPDF 等 PDF 庫來實現文件建立的自動化。 AutoFixture 可以產生文件所需的數據,而 IronPDF 可以將這些數據(格式為 HTML)有效率地轉換為 PDF 文件。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。