Enroll in Selenium Training

The next target is to test or run the feature file and in order to test the feature file, it is required to write the implementation or step definition for each step in the Step Definition File in C Sharp. When SpecFlow executes a Step in a Scenario it will look for a matching Step Definition to execute.

What is SpecFlow Step Definition file?

A Step Definition file is a small piece of code with a pattern attached to it or in other words a Step Definition is a C# method in a class with an annotation above it. An annotation followed by the pattern is used to link the Step Definition to all the matching Steps, and the code is what SpecFlow will execute when it sees a Gherkin Keywords.

How to Create a Step Definition file?

It is always good to have a nice and clean folder structure in the project and each folder represents the content in it. So, first create a folder for the Step Definition file.

Create a Step Definition File Folder

  1. Create a new Folder by right click on the ‘Project‘ and navigating to Add -> New Folder.

2) Name the folder as ‘Steps’ and hit enter.

StepDefinition_

Create a Step Definition File

1) Notice, the color of the statements mentioned in the feature file is violet. It means these statements do not have any definition attached to it. It is very easy to implement all the steps. Right-click on your feature file in the code editor and select Generate Step Definitions from the popup menu.

StepDefinition_2

2) This display a Pop Up window, which will ask to select the statements for which Step Definition file is to be created. Select all and click on Generate button. Do not forget to give it a logical name. In this case I named it as 'Login_Steps', as all the steps in this will file will be related to user Login.

StepDefinition_3

3) It will ask to specify the folder path to save the Step Definition file. As a new Steps folder was created to keep the definition file, mention the path for the same folder with the name of the Steps file. In this case, I have named it as 'LogIn_Steps'. Hit Save button to move forward.

StepDefinition_4

4) All the statements in the feature file will change the color now, it means these Feature statements are linked with Step Definitions.

  1. To have a look at the attached definitions, click on the any statement and press F12 button. This will open up the linked definition file and the cursor will be pointing to the linked definition.

StepDefinition_5

Step Definition method Implementation

This stuff is really easy if you know how to work with Selenium. In the last chapter of SpecFlow Feature File, we took a simple example of Selenium Test script for LogIn functionality. Now start picking up the code from the same Selenium Test Script and fit it into SpecFlow steps.

Add Selenium C# code in the Step Definition methods

  1. Take the code for following steps and fit it into the first method of Step Definition File:

Given User is at the Home Page‘.

  • Launch the Browser
  • Navigate to Home Page

Method will look like this now:

        [Given(@"User is at the Home Page")]
        public void GivenUserIsAtTheHomePage()
        {
            driver = new FirefoxDriver();
            driver.Url = "https://www.store.demoqa.com";
        }
  1. Take the code for following step and fit it into the second method of Step Definition File:

And Navigate to LogIn Page‘.

  • Click on the LogIn link

Method will look like this now:

     [Given(@"Navigate to LogIn Page")]
        public void GivenNavigateToLogInPage()
        {
            driver.FindElement(By.XPath(".//*[@id='account']/a")).Click();
        }
  1. Take the code for following step and fit it into the second method of Step Definition File:

When User enter UserName and Password‘.

  • Enter UserName and Password

Method will look like this now:

  [When(@"User enter UserName and Password")]
        public void WhenUserEnterUserNameAndPassword()
        {
            driver.FindElement(By.Id("log")).SendKeys("testuser_1");
            driver.FindElement(By.Id("pwd")).SendKeys("Test@123");
        }

  1. Take the code for following step and fit it into the second method of Step Definition File:

And Click on the LogIn button‘.

  • Click on Submit button

Method will look like this now:

        [When(@"Click on the LogIn button")]
        public void WhenClickOnTheLogInButton()
        {
            driver.FindElement(By.Id("login")).Click();
        }
  1. Take the code for the following step and fit it into the second method of Step Definition File:

Then Successful LogIN message should display‘.

  • LogOut Button should be displayed

Note: In the demo application, we do not have any successful message on positive LogIn, So we can verify that if the LogOut button is displayed once user is logged in. In case of failure, LogOut button will never display.

Method will look like this now:

    [Then(@"Successful LogIN message should display")]
        public void ThenSuccessfulLogINMessageShouldDisplay()
        {
            //This Checks that if the LogOut button is displayed
            true.Equals(driver.FindElement(By.XPath(".//*[@id='account_logout']/a")).Displayed);
        }

Complete Step Definition: LogIn_Steps

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using TechTalk.SpecFlow;

namespace SpecFlowDemo.Steps
{
    [Binding]
    public class LogIn_Steps
    {
        public IWebDriver driver;
        [Given(@"User is at the Home Page")]
        public void GivenUserIsAtTheHomePage()
        {
            driver = new FirefoxDriver();
            driver.Url = "https://www.store.demoqa.com";
        }

        [Given(@"Navigate to LogIn Page")]
        public void GivenNavigateToLogInPage()
        {
            driver.FindElement(By.XPath(".//*[@id='account']/a")).Click();
        }

        [When(@"User enter UserName and Password")]
        public void WhenUserEnterUserNameAndPassword()
        {
            driver.FindElement(By.Id("log")).SendKeys("testuser_1");
            driver.FindElement(By.Id("pwd")).SendKeys("Test@123");
        }

        [When(@"Click on the LogIn button")]
        public void WhenClickOnTheLogInButton()
        {
            driver.FindElement(By.Id("login")).Click();
        }

        [When(@"User LogOut from the Application")]
        public void WhenUserLogOutFromTheApplication()
        {
            ScenarioContext.Current.Pending();
        }

        [Then(@"Successful LogIN message should display")]
        public void ThenSuccessfulLogINMessageShouldDisplay()
        {
            //This Checks that if the LogOut button is displayed
            true.Equals(driver.FindElement(By.XPath(".//*[@id='account_logout']/a")).Displayed);
        }

        [Then(@"Successful LogOut message should display")]
        public void ThenSuccessfulLogOutMessageShouldDisplay()
        {
            ScenarioContext.Current.Pending();
        }
    }
}

Note: Please create your own UserName and Password on www.store.demoqa.com.

Note: In case get error on IWebDriver or FirefoxDriver keyword, it means Selenium dll is not yet added to Project Reference. Please take a look to Set Up Selenium on Visual Studio.

Run the SpecFlow Test

  1. To identify all the test in the Feature File, go to Test -> Windows -> Test Explorer.
  2. Notice, at the left side a new window is appeared called Test Explorer.
  3. Now to run a Feature Test, Right-click on the test in the Test Explorer window and select Run Selected Tests. This will run the selected test and display the output in the console window.

Note: There can be strong chances that the Test Explorer window will not show the default test. Kindly do a build by Build -> Build Solution.

Note: Feature File can also be run by Right-clicking in the feature and choosing Run SpecFlow Scenarios. But sometimes it creates issue.

SpecFlow starts it’s execution by reading the feature file steps. As soon as it reaches to the first step for e.g. Given statement of Scenario, it looks for the same statement in the Step Definition file, the moment it find the statement, it executes the piece of code written inside the function.

Feature File
Feature File
Previous Article
Data Driven Testing in SpecFlow
Data Driven Testing in SpecFlow
Next Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles

Feedback