.NET 幫助

Specflow C#(開發人員工作原理)

發佈 2024年7月1日
分享:

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 教程展示了這些工具如何協同工作以提升你的應用程序開發過程。

Specflow C# 入門

在 .NET 專案中設定 Specflow

要在您的 .NET 專案中開始使用 Specflow,首先需要安裝 Specflow NuGet 套件來設置您的測試框架,創建功能文件,並定義測試情境。

  1. 打開 Visual Studio。
  2. 創建一個新的 .NET 專案或打開已存在的專案。
  3. 前往「擴充功能」選單,然後選擇「管理擴充功能」。
  4. 搜尋 "Specflow"。安裝 Specflow 擴充功能。

Specflow C#(對開發人員的工作原理):圖1

基本範例程式碼

當 Specflow 設置完成後,您可以在 features 資料夾中創建您的第一個功能文件。在 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
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
Feature:
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'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
VB   C#

此功能檔案描述了一個基本的登錄過程。Given 設置了測試的場景。When 描述了動作。Then 定義了預期的結果。您使用簡單的英語編寫這些語句,這讓人們容易理解測試的流程和目的。

實作 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
VB   C#

這個 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
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
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在您的步驟定義中,您可以按照以下方式訪問這些資料:

[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
VB   C#

與測試瀏覽器的整合

Specflow 與 Visual Studio 的測試瀏覽器整合,您可以在那裡高效地運行和管理所有測試。這使得運行和管理測試變得簡單。確保您的項目已正確配置。一旦您構建項目,測試將出現在測試瀏覽器中。您可以運行單個測試或一次運行所有測試。

平行測試執行

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
VB   C#

自訂掛鉤是一個強大的功能。它們幫助您管理測試設置和拆卸過程。

本節涵蓋了 Specflow 五個關鍵功能,可以增強您在 .NET 專案中的測試框架。每個功能都旨在提高您的測試自動化工作的靈活性和效率。

將 Specflow C# 與 IronPDF 整合

Specflow C#(它如何為開發人員運作):圖2

IronPDF是一個適用於C#的程式庫,使開發人員可以在.NET應用程式中生成、操作和渲染PDF文件。這個強大的工具與Specflow一起使用時,可以成為您行為驅動開發的測試武器的寶貴補充。 (BDD) 框架 .NET。

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

結合 IronPDF 與 Specflow C# 的使用案例

結合 IronPDF 與 Specflow 的一個實際使用案例是驗證資料夾報表的內容和格式是否正確。例如,您可以自動測試報告中是否包含正確的數據、是否符合預期的佈局並且在規定的要求內易於訪問。這種集成在需要準確文件(如發票或合規報告)至關重要的情況下特別有用。

請確保您已安裝 IronPDF。您可以使用 NuGet 套件管理主控台來安裝它:

Install-Package IronPdf

Specflow C#(它如何為開發人員工作):圖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)
    {
        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)
    {
        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)
		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
VB   C#

在這段程式碼中,我們定義了一個Specflow步驟,首先從指定的路徑載入PDF,然後驗證該PDF包含預期的文字。我們使用 IronPdf.PdfDocument 類來載入和操作PDF檔案。這種設置允許您將PDF驗證整合到自動化測試中,使捕捉錯誤變得更容易。

結論

Specflow C#(開發人員運作方式):圖 4

總之,結合Specflow C#和IronPDF可以提升您的.NET專案的功能,特別是在處理PDF文件時。Specflow擅長使用簡單語言定義和執行詳細的測試場景。

IronPDF則通過提供強大的PDF操作功能來補充這一點。通過集成這兩個強大的工具,您可以簡化您的測試過程。如果您想試驗這些功能,IronPDF提供免費試用。

< 上一頁
Octokit .NET(如何為開發人員運作)
下一個 >
Dotnetopenauth .NET Core(它如何為開發人員工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >