Skip to main content

Data Driven Testing with Examples Keyword in Specflow

             SpecFlow supports Data Driven testing by default, thanks to the Scenario outline and Examples section. With these keywords, SpecFlow enables simple Data Driven testing to be completed without requiring any changes to the C# file. We will learn how to use examples to implement Scenario Outlines in Data Driven Testing. What is the keyword?

Only the Example keyword can be used with the Scenario Outline keyword.

Scenario Outline – Run the same scenario for two or more different sets of test data with this. In our scenario, for example, if you'd like to register another user, you can data drive a same scenario twice.

Examples – All scenario outlines must be followed by the Examples section. This section contains the data that needs to be passed on to the scenario.

Data Driven Testing with Examples

  • 1) In the Feature file, change the Scenario keyword to Scenario Outline.
  • 2) Enter the Example Data just below the Feature File's Users Scenario.
  • Examples:

       | username | statuscode |

       | 1        | 200        |

       | 100      | 404        |

            The Examples portion is a table in which each argument variable represents a column in the table and is divided by "|." Each line beneath the header represents a single run of the test case with the specified data. As a result, if there are three lines below the header in the Examples table, the script will run three times with each data set.
    
The following are the feature and step definition files for the test:

Users.feature file

Feature: Users

       Operations about user

 

Background:

       Given I perform api operation on petstore server https://petstore.swagger.io/v2/

 

Scenario Outline: GET operation with example

       When I perform GET operation for user using endpoint "/user/{username}" by using User      name "<username>"

       Then I should see the response as successful with status code as <statuscode> ok

 

       Examples:

       | username | statuscode |

       | Raju     | 200        |

       | Ramesh   | 404        |

       |          | 405        |

UsersSteps.cs file

using Microsoft.VisualStudio.TestTools.UnitTesting; //For asserting

using Newtonsoft.Json.Linq; //For Json object creation

using RestSharp; //For RestSharp operation

using System; //for Basic C# package

using TechTalk.SpecFlow; //for BDD package

 

namespace APIAutomation.Features

{

    [Binding] //It's binding the feature file with step definition file

    public class UsersSteps

    {

        public RestClient client;

        public RestRequest request;

        public IRestResponse response;

 

 

 

        [Given(@"I perform api operation on petstore server ""(.*)""")]

        public void GivenIPerformApiOperationOnPetstoreServer(string baseUrl)

        {

            //Make a Request that points to the Service Endpoint.

            client = new RestClient(baseUrl);

        }

[When ( @"I perform GET operation for user using endpoint ""(.*)"" by using User name ""(.*)""")]

        public void WhenIPerformGETOperationForUserUsingEndpointByUsingUserName(string endpoint, string username)

        {

            //Create a GET request with the given endpoint.

            request = new RestRequest(endpoint, Method.GET);

            //passing url segment

            request.AddParameter("username", username, ParameterType.UrlSegment);

            //execute the request

            response = client.Execute(request);

        }

[Then(@"I should see the response as successful with status code as (.*) ok")]

        public void ThenIShouldSeeTheResponseAsSuccessfulWithStatusCodeAsOk(int status)

        {

            //Converting the response status code to integer format

            int statusCode = (int)response.StatusCode;

 

            //Asserting the response's status code

            Assert.AreEqual(status, statusCode, "Statuscode is not a " + status);

        }

    }

}

        To run a Feature Test, right-click on it in the Test Explorer window and choose Run Selected Tests. This will execute the specified test and display the results in the console window.

Note: The Feature File could also be run by right-clicking on it and selecting Run SpecFlow Scenarios. However, it can occasionally cause problems.



        This takes parameter a step further: our scenario now has "variables," which are filled in by the attributes in each row. To also be clear, by specifying this, the scenario will run three times, each time passing through one row at a time. This makes it extremely simple to define a large number of examples, edge cases, and special outcomes. Variables are defined in the Examples section a rather than hardcoding the test data.

                   Specflow Tables

Helpers for SpecFlow:

        Tables in Specflow are very useful and can be used in a variety of ways. Tables are also useful for dealing with large amounts of data. They are quite powerful, but not the most user-friendly because you must deal with dictionary objects, plain class objects, and collections.

        Tables are part of the SpecFlow Assist Helpers package. We need to add the TechTalk.SpecFlow.Assist namespace to the top of your file in order to use these helpers.

    using TechTalk.SpecFlow.Assist;

Most people are confused by the Tables & Scenarios outline, but these two work in completely different ways.


The following are the differences between Scenario Outline and Table

Scenario Outline:

  • This uses the Example keyword to define the test data for the Scenario
  • This works for the entire test
  • Cucumber runs the entire test as many times as the number of data points in the Test Set.

Tables:

  • The test data is defined without the use of a keyword.
  • This only works for the single step defined below
  • A separate code is required to understand the test data, and it can then be run once or multiple times, but only for the single step, not the entire test.

Comments

Popular posts from this blog

Specflow Tables – Convert Table to Dictionary

            Tables can be used both vertically and horizontally. In the first table examples, we'll use the Data Vertically as a Key-Value pair, which the Dictionary object allows. 1) Add a New Step The first step is to create a new Step that will accept data in the form of a table. It is once again simple to specify data for the step in Vertical format. Let's look at how to pass Vertical Data in the same Users scenario that was used in the previous SpecFlow :   Feature : Users        Operations about user   Background :        Given I perform api operation on petstore server " https://petstore.swagger.io/v2/ "   Scenario : POST operation with table        When I perform POST operation for User using endpoint " /user " using table data               | Key         | Value                |               | Id          | 2                    |               | username    | Ravi                 |               | firstname   |

Specflow Tables – Convert Table to Data Table

                 Vertical Data Using Tables was covered in the previous chapter of Covert Table into Dictionary. When we have a long list of Data, this is useful. Personal information includes first and last name, address, and job title, among other things.                However, this has some limitations. For example, if we want to repeat the same step, it is difficult to manage with a Dictionary Key-Value pair. To obtain the functionality, Horizontal Data must be used rather than Vertical Data, which can be accomplished by using the “Convert Table into Data Table” command. Table to Data Table Conversion We will use the same example of the Users Feature and modify it to suit our needs. Before proceeding, please review the first chapter of Data Driven Testing and see how the basic functionality works for the Users Scenario. 1) Add a New Step The first step is to create a new Step that will accept data in the form of a table. It is once again simple to specify data for the st

Json Response Deserialization

  How Do I Deserialize a JSON Response to a Class Using Rest Sharp? Let's continue from the earlier section, Creating a POST request with Rest-Sharp. In the earlier section, we made a successful post request and received the Response body shown below. To validate parts of the Response body, we used JObject.Parse. We will make this Response body into a Class. Deserialization of JSON refers to the process of converting a JSON or any structured data, including XML, into a programming class. Deserialization refers to the process of converting JSON from its String form to its Class form. This is also known as structured data object representation. JSON is used to represent structured data in this case. To integrate the JSON to a Class representation, we will first create a Class that contains all of the nodes in the JSON. There are three nodes in the Success response above. ·          Success code ·          Type ·          Message String is the value of these three nodes