跳過到頁腳內容
.NET幫助

Specflow C#(對於開發者的運行原理)

Specflow C#

Specflow C# 是一個開放源碼的測試框架,支援行為驅動開發 (BDD),並允許您為測試情境建立特徵檔案。 它可與 .NET Framework 專案無縫整合。

您可以用淺顯易懂的語言描述測試。 此方法可促進開發人員與非開發人員之間的合作。 每個人都可以為測試情境貢獻心力。 Specflow 主要使用功能檔案來管理和執行功能資料夾中的所有測試。

IronPDF 則是一個專注於在 .NET 內操作 PDF 的函式庫。 它可讓您輕鬆建立、編輯和閱讀 PDF 檔案。 您可以直接將 HTML 轉換成 PDF。 此功能對於在您的應用程式中產生報告或文件特別有用。 IronPDF 與各種版本的 .NET 相容,包括 Core、Framework 和 Standard。

雖然 Specflow C# 和 IronPDF 的用途不同,但它們都是開發人員工具包中的重要工具。 它們可以在專案中有效結合。 例如,您可以使用 Specflow C# 定義並測試資料擷取與處理的功能,然後運用 IronPDF 根據測試結果產生報告。 本Specflow 與 IronPDF 整合教學展示了這些工具如何相互配合以增強您的應用程式開發流程。

Getting Started with Specflow C#

在 .NET 專案中設定 Specflow

若要開始在您的 .NET 專案中使用 Specflow,您首先需要安裝 Specflow NuGet 套件,以設定您的測試框架、建立功能檔案以及定義測試情境。

1.開啟 Visual Studio。 2.建立新的 .NET 專案或開啟現有的專案。 3.移至 Extensions 功能表,然後選取 Manage Extensions。 4.搜尋"Specflow"。 安裝 Specflow 擴充套件。

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

基本程式碼範例

一旦 Specflow 設定完成,您就可以建立您的第一個功能檔案,該檔案將儲存在功能資料夾中。 Specflow 中的功能檔案會以可讀的格式概述您想要測試的行為。 以下是一個簡單的範例,說明如何建立新的功能檔案並定義應用情境:

Feature: Login Feature
    Scenario: Successful Login with Valid Credentials
        Given I am on the login page
        When I enter valid credentials
        Then I should be redirected to the dashboard

此功能檔案描述基本的登入流程。 Given 為測試設定場景。 When 描述操作。 Then 定義了預期結果。 您以簡明的英文撰寫這些說明。 這樣才能讓人輕鬆了解測試的流程和目的。

Implement Features of Specflow C#

使用步驟定義來撰寫測試

在 Specflow 中,測試由功能檔案中概述的情境驅動。 為了讓這些情境可執行,您需要步驟定義。 步驟定義將普通語言步驟與 C# 代碼綁定。 以下是如何定義步驟定義:

[Binding]
public class LoginSteps
{
    [Given(@"I am on the login page")]
    public void GivenIAmOnTheLoginPage()
    {
        // Code to navigate to the login page
    }

    [When(@"I enter valid credentials")]
    public void WhenIEnterValidCredentials()
    {
        // Code to input username and password
    }

    [Then(@"I should be redirected to the dashboard")]
    public void ThenIShouldBeRedirectedToTheDashboard()
    {
        // Code to verify the dashboard is displayed
    }
}
[Binding]
public class LoginSteps
{
    [Given(@"I am on the login page")]
    public void GivenIAmOnTheLoginPage()
    {
        // Code to navigate to the login page
    }

    [When(@"I enter valid credentials")]
    public void WhenIEnterValidCredentials()
    {
        // Code to input username and password
    }

    [Then(@"I should be redirected to the dashboard")]
    public void ThenIShouldBeRedirectedToTheDashboard()
    {
        // Code to verify the dashboard is displayed
    }
}
<Binding>
Public Class LoginSteps
	<Given("I am on the login page")>
	Public Sub GivenIAmOnTheLoginPage()
		' Code to navigate to the login page
	End Sub

	<[When]("I enter valid credentials")>
	Public Sub WhenIEnterValidCredentials()
		' Code to input username and password
	End Sub

	<[Then]("I should be redirected to the dashboard")>
	Public Sub ThenIShouldBeRedirectedToTheDashboard()
		' Code to verify the dashboard is displayed
	End Sub
End Class
$vbLabelText   $csharpLabel

此 C# 類代表登入情境的步驟。 每個方法都標記了與步驟類型相對應的 Specflow 屬性,例如用於識別特定步驟的字串鍵。

資料驅動測試

Specflow 支援資料驅動測試,允許您在情境中利用各種測試資料集。 這可讓您使用各種資料集測試情境。 以下是使用功能檔案中的表格的範例:

Scenario: Login with multiple users
    Given I am on the login page
    When I login with the following credentials:
        | Username  | Password |
        | user1     | pass1    |
        | user2     | pass2    |
    Then I should see user specific dashboard

在您的步驟定義中,您可以如下方式存取這些資料:

[When(@"I login with the following credentials:")]
public void WhenILoginWithTheFollowingCredentials(Table table)
{
    foreach(var row in table.Rows)
    {
        string username = row["Username"];
        string password = row["Password"];
        // Code to perform login
    }
}
[When(@"I login with the following credentials:")]
public void WhenILoginWithTheFollowingCredentials(Table table)
{
    foreach(var row in table.Rows)
    {
        string username = row["Username"];
        string password = row["Password"];
        // Code to perform login
    }
}
<[When]("I login with the following credentials:")>
Public Sub WhenILoginWithTheFollowingCredentials(ByVal table As Table)
	For Each row In table.Rows
		Dim username As String = row("Username")
		Dim password As String = row("Password")
		' Code to perform login
	Next row
End Sub
$vbLabelText   $csharpLabel

與 Test Explorer 整合

Specflow 與 Visual Studio 的 Test Explorer 整合,您可以在其中有效率地執行和管理所有測試。 這可讓您輕鬆執行和管理測試。 確保您的專案配置正確。 一旦您建立專案,您的測試就會出現在 Test Explorer 中。 您可以執行單獨測試或一次執行所有測試。

平行測試執行

Specflow 支援執行平行測試,以縮短整體執行時間。這可縮短執行所有測試所需的時間。 您需要設定您的 specflow.json 檔案或 AssemblyInfo.cs 檔案以啟用並行執行:

{
  "specFlow": {
    "runtime": {
      "testThreadCount": 4,
      "testSchedulingMode": "Parallel"
    }
  }
}

此配置最多可讓四個測試同時執行。

自訂鉤子

Specflow 允許您定義自訂鉤子。 這些鉤子可以在測試生命週期中的各個階段執行程式碼。 以下是如何在任何測試執行之前定義設定資料庫的鉤子:

[BeforeTestRun]
public static void SetUpDatabase()
{
    // Code to set up database
}
[BeforeTestRun]
public static void SetUpDatabase()
{
    // Code to set up database
}
<BeforeTestRun>
Public Shared Sub SetUpDatabase()
	' Code to set up database
End Sub
$vbLabelText   $csharpLabel

自訂鉤子是一項強大的功能。 這些工具可協助您管理測試設定與拆解流程。

本節涵蓋 Specflow 的五個主要功能,這些功能可以增強您在 .NET 專案中的測試框架。 每個功能的設計都是為了提高您測試自動化工作的彈性和效率。

將 Specflow C# 與 IronPDF 整合

Specflow C# (How It Works For Developers):圖 2

IronPDF 是用於 C# 的函式庫,可讓開發人員在 .NET 應用程式中產生、處理和渲染 PDF 檔案。 當這個強大的工具與 Specflow(.NET 的行為驅動開發 (BDD) 框架)一起使用時,可以成為您的測試武器庫的重要補充。

透過整合 IronPDF,您可以自動測試應用程式中的 PDF 輸出,確保它們符合所需的規格。

Use Case of Merging IronPDF with Specflow C#

將 IronPDF 與 Specflow 結合的一個實際用例是驗證應用程式所產生 PDF 報告的內容與格式。 例如,您可以自動測試報告是否包含正確的資料、是否符合預期的版面設計,以及是否可在規定的要求內存取。 這種整合在準確的文件(如發票或合規性報告)非常重要的情況下特別有用。

請確定您已安裝 IronPDF。 您可以使用 NuGet 套件主控台進行安裝:

Install-Package IronPdf

Specflow C# (How It Works For Developers):圖 3

使用個案的程式碼範例

以下是一個完整的程式碼範例,示範如何設定 SpecFlow 步驟定義,以使用 IronPDF 測試 PDF 內容。 本範例假設您正在測試應用程式所產生的 PDF 文件,該文件應包含特定文字:

using IronPdf;
using TechTalk.SpecFlow;

[Binding]
public class PdfContentSteps
{
    private string? _pdfPath;
    private PdfDocument? _pdfDocument;

    [Given(@"a PDF file generated at '(.*)'")]
    public void GivenAPDFFileGeneratedAt(string pdfPath)
    {
        _pdfPath = pdfPath;
        _pdfDocument = new PdfDocument(_pdfPath);
    }

    [Then(@"the PDF should contain the text '(.*)'")]
    public void ThenThePDFShouldContainTheText(string expectedText)
    {
        // Extract text from the PDF and check if it contains the expected text
        var textContent = _pdfDocument.ExtractAllText();
        if (!textContent.Contains(expectedText))
        {
            throw new Exception("PDF content does not contain the expected text.");
        }
    }
}
using IronPdf;
using TechTalk.SpecFlow;

[Binding]
public class PdfContentSteps
{
    private string? _pdfPath;
    private PdfDocument? _pdfDocument;

    [Given(@"a PDF file generated at '(.*)'")]
    public void GivenAPDFFileGeneratedAt(string pdfPath)
    {
        _pdfPath = pdfPath;
        _pdfDocument = new PdfDocument(_pdfPath);
    }

    [Then(@"the PDF should contain the text '(.*)'")]
    public void ThenThePDFShouldContainTheText(string expectedText)
    {
        // Extract text from the PDF and check if it contains the expected text
        var textContent = _pdfDocument.ExtractAllText();
        if (!textContent.Contains(expectedText))
        {
            throw new Exception("PDF content does not contain the expected text.");
        }
    }
}
Imports IronPdf
Imports TechTalk.SpecFlow

<Binding>
Public Class PdfContentSteps
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: private string? _pdfPath;
	Private _pdfPath As String
	Private _pdfDocument? As PdfDocument

	<Given("a PDF file generated at '(.*)'")>
	Public Sub GivenAPDFFileGeneratedAt(ByVal pdfPath As String)
		_pdfPath = pdfPath
		_pdfDocument = New PdfDocument(_pdfPath)
	End Sub

	<[Then]("the PDF should contain the text '(.*)'")>
	Public Sub ThenThePDFShouldContainTheText(ByVal expectedText As String)
		' Extract text from the PDF and check if it contains the expected text
		Dim textContent = _pdfDocument.ExtractAllText()
		If Not textContent.Contains(expectedText) Then
			Throw New Exception("PDF content does not contain the expected text.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

在此程式碼中,我們定義了 Specflow 步驟,該步驟會先從指定路徑載入 PDF,然後驗證這個 PDF 是否包含預期的文字。 IronPdf.PdfDocument 類別用於載入和操作 PDF 檔案。此設定可讓您將 PDF 驗證整合到自動化測試中,從而更容易捕獲錯誤。

結論

Specflow C# (How It Works For Developers):圖 4

總而言之,結合 Specflow C# 與 IronPDF 可增強您的 .NET 專案能力,尤其是在處理 PDF 文件時。 Specflow 擅長使用淺白的語言定義和執行詳細的測試方案。

IronPDF 提供了強大的 PDF 操作功能,與此相輔相成。 透過整合這兩種強大的工具,您可以簡化測試流程。 如果您想試用這些功能,免費試用 IronPDF

常見問題解答

什麼是 Specflow C# 及其如何支持 BDD?

Specflow C# 是一個為行為驅動開發(BDD)設計的開源測試框架。它允許開發人員使用簡單語言創建功能文件,以概述測試場景,促進開發者和非開發者之間的協作。

如何將 Specflow 與 IronPDF 整合進行報告生成?

Specflow 可以用來定義和測試應用程式中的數據處理功能,IronPDF 可以用於根據測試結果生成 PDF 報告,確保報告符合指定標準。

什麼是功能文件,它們在 Specflow 中如何運作?

Specflow 的功能文件是使用簡單語言概述測試場景的文件。它們通過明確定義需要測試的行為來幫助管理和執行測試,使其對技術和非技術人員皆可理解。

Specflow 和 IronPDF 可以有效結合使用嗎?

是的,當 Specflow 管理測試場景時,IronPDF 可以用於生成和操控 PDF 作為測試過程的一部分,例如從測試數據製作報告。

開始使用 Specflow 涉及哪些步驟?

要開始使用 Specflow,開發人員需要安裝 Specflow NuGet 包,為測試場景創建功能文件,並定義將場景與 C# 代碼綁定的步驟定義。

Specflow 如何支持數據驅動測試?

Specflow 通過允許在場景中使用不同的測試數據集來支持數據驅動測試,這有助於驗證應用程式在各種條件下的行為。

自定義鉤子在 Specflow 中起什麼作用?

Specflow 中的自定義鉤子允許開發人員在測試週期的不同點執行特定代碼,例如在測試運行之前初始化測試數據庫或在測試完成後清理。

Specflow 如何與 Visual Studio 的測試資源管理器集成?

Specflow 無縫整合進 Visual Studio 的測試資源管理器,使開發人員能夠直接在 IDE 中運行、管理和調試測試,前提是項目配置正確。

Specflow 支持並行測試執行嗎?

是的,Specflow 支持並行測試執行,可以在 `specflow.json` 文件中進行配置,以通過並行運行測試來減少總測試時間。

IronPDF 如何自動化 Specflow 中的 PDF 輸出測試?

IronPDF 可以與 Specflow 結合使用,實現 PDF 輸出的驗證自動化,確保生成的文檔符合特定要求,且沒有錯誤。

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 小時在線上。
聊天
電子郵件
打電話給我