SpecFlow - 使用CreateSet的表格



CreateSet<T> 是 Table 方法的擴充套件。它將表格中的資料轉換為一組物件。這是在水平方向進行資料引數化的一種常用技術。

我們可以使用此方法處理一行或多行資料。SpecFlow Assist Helpers 包用於處理表格。此外,我們還必須將名稱空間TechTalk.SpecFlow.Assist新增到我們的程式碼中。

CreateSet<T> 方法根據表格中匹配的資料獲取一個IEnumerable<T>。它包含所有物件的值。它確保從字串到關聯屬性的型別轉換正確。

步驟 1:建立功能檔案

關於如何建立功能檔案的詳細資訊在“功能檔案”章節中詳細討論。

Feature: User credential

Scenario: Login module
   When User types details
   | Name | Password |
   | t1   | pwd      |
   | t2   | pwd1     |
Then user should be able to login

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

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

選擇新建資料夾選項。

String Object

將資料夾命名為Utils

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

Folder created

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

Folders Created

專案資料夾結構

Folders Structures

C# 類實現

using System;
using System.Collections.Generic;
using System.Text;
namespace SpecFlowProject1.Utils {
   class Class1 {
      public class Input {
         //two string objects declared
         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 Table data with CreateSet method
         var i = t.CreateSet<Utils.Class1.Input>();
         
         //iterate over rows
         foreach (var r in i) {
            Console.WriteLine(r.Input1);
            Console.WriteLine(r.Input2);
         }
      }
      [Then(@"user should be able to login")]
      public void ThenUserShouldBeAbleToLogin() {
         Console.WriteLine("User should be able to login");
      }
   }
}

步驟 4:執行和結果

選擇使用者憑據(1) 功能,然後單擊檢視中的“執行所有測試”。

Test Views

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

Additional Outputs

Scenario link

該場景已執行,資料透過功能檔案中的表格在 When 步驟中使用 CreateSet 方法傳遞。

廣告