SpecFlow - 使用 CreateInstance 的表格



CreateInstance<T> 是 Table 方法的擴充套件。它將 Table 中的資料轉換為物件。它是垂直對齊資料引數化的一種流行技術。

SpecFlow Assist Helpers 包用於處理表格。此外,我們還必須將名稱空間 TechTalk.SpecFlow.Assist 新增到我們的程式碼中。

特性檔案中 Table 的標題可以是任何名稱,例如:KEY、VALUE。但是,第一列應指向屬性的名稱,第二列應指向其對應值。

步驟 1:建立特性檔案

關於如何建立特性檔案的詳細資訊在“特性檔案”章節中進行了詳細討論。

Feature: User credential

Scenario: Login module
   When User types details
   | KEY      | VALUE          |
   | username | tutorialspoint |
   | password | pwd1           |
Then user should be able to login

步驟 2:建立 C# 檔案以訪問字串物件

我們將在專案中建立一個新資料夾,並在其中包含一個 C# 檔案。右鍵單擊SpecFlow 專案,然後單擊新增

選擇新建資料夾選項。

String Objects

將資料夾命名為Utils

右鍵單擊建立的新資料夾,然後選擇新增選項。單擊

New Folder

在搜尋框中鍵入C# 類並搜尋。從搜尋結果中選擇選項,然後單擊新增繼續。

New Folders

專案資料夾結構

Folder Structures

C# 類實現

using System;
using System.Collections.Generic;
using System.Text;
namespace SpecFlowProject1.Utils {
   class Class1 {
      public class Input {
         //Declaring string objects
         public string Input1 { get; set; }
         public string Input2 { get; set; }
      }
   }
}

步驟 3:建立步驟定義檔案

關於如何建立步驟定義檔案的詳細資訊在“步驟定義檔案”章節中進行了詳細討論。

using System;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;
namespace SpecFlowProject1.Features {
   [Binding]
   public class UserCredentialSteps {
      [When(@"User types details")]
      public void WhenUserTypesDetails(Table t) {
         //access data with CreateInstance method using C# class method
         var i = t.CreateInstance<Utils.Class1.Input>();
         Console.WriteLine(i.Input1);
         Console.WriteLine(i.Input2);
      }
      [Then(@"user should be able to login")]
      public void ThenUserShouldBeAbleToLogin() {
         Console.WriteLine("User should be able to login");
      }
   }
}

步驟 4:執行和結果

選擇使用者憑據(1)特性,然後單擊執行檢視中的所有測試

Definition File

選擇登入模組場景,然後單擊開啟此結果的附加輸出連結

Definition Files

Definitions File

該場景已執行,資料透過 When 步驟中使用 CreateInstance 方法的特性檔案中的表格傳遞。

廣告

© . All rights reserved.