SpecFlow - Step Definition File



To execute the Feature file, we must add the implementation logic for each of the steps. To add the definition of the step in SpecFlow, the C# language is used. Thus, a Step Definition File contains methods developed in C# within a Class.

The methods have annotations along with a pattern to connect the Step Definition to every matching step. The SpecFlow shall run the code to execute the keywords in Gherkin.

A Step Definition file is a link between the application interfaces and Feature File. For providing readability features, the Step Definition File can have parameters. This signifies that it is not required to have a step definition for each step that has a minor difference.

For instance, Given Login to admin application and Given Login to payment application steps can be automated with one step definition by passing admin and payment as parameters. The regular expression (.*) is used to declare parameters for a method.

Rules for Regular expressions

The rules for regular expressions are listed below −

  • It is matched with the complete step, even though we are not using the markers ^ and $.

  • The capturing groups in the regular expression describe the parameters for the method in order.

Rules for Step Definition Methods

The rules to be followed for Step Definition methods are listed below −

  • It should have a [Binding] attribute and reside within a public class.

  • It can either have a static or non-static method. If it is a non-static method, an object should be instantiated once for every scenario of the class where it resides.

  • It should not have ref or out parameters.

  • It cannot have a return type.

Step Definition File Creation

Right-click on any step of the Feature File, then click on Generate Step Definitions option.

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

Step Definition

In the Generate Step Definition Skeleton pop-up, check the steps for which we want to generate the implementation. Add a Class Name, then click on the Generate button.

Step Skeleton

Give the location of saving the Step Definition File and then click on Save.

Step Saving

The Step Definition File gets opened with for all the matching steps in the Feature File. It also contains regular expression attributes.

Step Opened

Project Folder after Step Definition File Creation

Following is the project folder after the step definition file is created −

Step Definition
Advertisements