SpecFlow - Table with CreateInstance



CreateInstance<T> is an extension of the Table method. It transforms the data in the Table to an object. It is one of the popular techniques to have parameterization of data in a vertical alignment.

The SpecFlow Assist Helpers package is used to work on tables. Also, we have to add namespace TechTalk.SpecFlow.Assist to our code.

The Table headers in the Feature File can be of any name, for example: KEY, VALUE. However, the first column should point to the name of the property and the second column should point to its corresponding value.

Step 1: Create a Feature File

The details of how to create a Feature File is discussed in detail in the Chapter − Feature File.

Feature: User credential

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

Step 2: Create C# File to access String Objects

We shall create a new folder within the project and have a C# file in it. Right-click on the SpecFlow Project, then click on Add.

Select the option New Folder.

String Objects

Give the name Utils to the folder.

Right-click on the new Folder created, then select the option Add. Click on Class.

New Folder

Type C# Class in the search box and search. Select the option Class from the search result and then click on Add to proceed.

New Folders

Project Folder Structure

Folder Structures

C# Class Implementation

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; }
      }
   }
}

Step 3: Create a Step Definition File

The details of how to create a Step Definition File is discussed in detail in the Chapter − Step Definition File.

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");
      }
   }
}

Step 4: Execution & Results

Select User credential(1) Feature, then click on Run All Tests in View.

Definition File

Select Login Module Scenario, then click on Open additional output for this result link.

Definition Files

Definitions File

The Scenario got executed with data passed from a Table in the feature file within the When step using CreateInstance method.

Advertisements