SpecFlow BDD Tutorial for .NET Testing
SpecFlow BDD Tutorial for .NET Testing
i
SpecFlow
Audience
This tutorial designed for professionals working in software who want to collaborate among
the developers, testers, business analysts, and other stakeholders of the project. The
tutorial will be helpful for both the developers and business analysts.
Prerequisites
Before reading this tutorial, you should have a fair knowledge on basics in testing. Also,
an expertise on the language C# would be an added advantage for understanding the
practical examples in SpecFlow discussed here.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@[Link]
ii
SpecFlow
Table of Contents
About the Tutorial ........................................................................................................................................... ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
Components .................................................................................................................................................... 1
BDD Methodologies......................................................................................................................................... 6
Installation ....................................................................................................................................................... 8
Installation ..................................................................................................................................................... 17
iii
SpecFlow
Feature .......................................................................................................................................................... 46
Tags................................................................................................................................................................ 47
Scenario ......................................................................................................................................................... 49
Given.............................................................................................................................................................. 49
When ............................................................................................................................................................. 50
Then ............................................................................................................................................................... 50
Background .................................................................................................................................................... 51
Data Table...................................................................................................................................................... 53
v
1. SpecFlow — Introduction SpecFlow
SpecFlow is an open-source test automation tool built on BDD model. It is mostly used to
build automation tests for projects built in .NET. This tutorial will provide knowledge on
SpecFlow and its features.
Components
SpecFlow’ s primary task is to bind Feature files written in Gherkin. SpecFlow+ Runner is
the test runner which has the execution capabilities and reports generation. This also
comes without cost and we need to create a SpecFlow account for it.
SpecFlow+ LivingDoc is a group of tools that keeps the Gherkin Feature File in a
readable format. This can be shared with the stakeholders in the team who are not well
versed with tools like Visual Studio.
SpecFlow+ LivingDoc Generator is a group of plugins and tools for SpecFlow to produce
documentation from the Gherkin Feature File. This does not require an account to be
created and can be easily shared with others.
In the Visual Studio, click on Edit, then select Intellisense to get the various options.
1
SpecFlow
There are multiple options from the Edit menu to customize various sections of the Feature
file.
We can define our own feature file template to open when creating a new test
case.
2
SpecFlow
Formatting tables
We can modify the table size and format it automatically as we type the names of the
column and enter its values.
But SpecFlow is not confined to Visual Studio only, it can be used with Mono and VSCode
also.
3
2. SpecFlow — Test Driven Development SpecFlow
A Test-Driven Development is also known as the TDD. It consists of the below steps to
be followed one-by-one:
Step 4: Start code refractor and redo all the above steps till the development is done.
Benefits of TDD
The benefits of TDD are listed below:
The implementation for a module is done only if all the test cases pass and code
refactoring is complete. Thus, verification and refactoring should be done prior to
moving it to the next test.
If a bug is found, a test is created to get the details of the bug. The script is updated,
to pass the tests. Simultaneously, the other tests are also executed to ensure that
existing features are not broken by the fix.
A developer can participate in design decisions and improve it anytime during the
test execution stage to ensure the application is working correctly. This is done to
increase the maintainability of the product.
A developer is sure of making any modifications. This is because if that affects any
existing feature, it shall be reflected by executing the tests. This way bugs can be
addressed quickly.
On running the tests in succession¸ all the prior bug fixes are also verified, and the
similar bugs can be avoided.
4
SpecFlow
Since major testing is conducted during the development phase, the test duration
required prior to delivery is short.
Drawbacks of TDD
The drawbacks of TDD are listed below:
Myths Facts
TDD is only concerned with testing with TDD is a development technique following
automation. the Test First method.
TDD does not consist of design. TDD has a thorough research and design
depending on the requirements. The
design is completed during the
development phase.
TDD is done only for unit testing. TDD is done for system and integration
testing as well.
TDD cannot be adopted for orthodox test TDD is used for Agile development. But it
projects. can be adopted for conventional test
projects as well.
5
3. SpecFlow - Behaviour Driven Development SpecFlow
Behaviour Driven Development also known as BDD has the features listed below:
Gives a shared method and tools which help to establish interaction with the
developers, business analyst, and other stakeholders to work together for the
product development.
Ensures that the delivered product adds the necessary business value.
Finds out the capabilities of the system and how it should be developed.
Ensures that the product is presentable and has a good structure.
Checks the functionalities of the software and ensures that the end user
expectations are met.
BDD Methodologies
The primary methodologies adopted by BDD are listed below:
Specification By Example
It utilizes examples in interactions to describe the software characteristics and its business
scenarios. This methodology helps to remove any knowledge gap on the business
requirements among the developers, testers, product owners, business analysts and all
other stakeholders in the team.
BDD Tool
SpecFlow is one of the BDD tools that is open source. It contains a Feature file which
follows the Gherkin syntax. The source code of SpecFlow is hosted on GitHub. It is mostly
used to build automation tests for projects built in .NET. It is similar to Cucumber in its
functionalities.
6
SpecFlow
It consists of the Feature, Background scenario, and two Scenarios. The Feature File
consists of the acceptance standard for a Feature in the application.
7
4. SpecFlow — Visual Studio Installation SpecFlow
In this chapter, we shall see the process of installation of Visual Studio and project
configuration.
Installation
Navigate to the link: [Link]
[Link]
For the Community version of Visual Studio, click on Free download under the
Community section.
Visual Studio Installer pop-up comes up. Click on Continue. Download and installation
process begins.
8
SpecFlow
Once installation is done, select the option .NET desktop development. Then click on
Install.
9
SpecFlow
10
SpecFlow
Along with it, Visual Studio pop-up appears. If you do not have an existing
11
SpecFlow
12
SpecFlow
Project Configuration
Once the Visual Studio landing page gets opened, click on Create a new project.
13
SpecFlow
We shall create a new C# class library. Enter class library core in the search box. Choose
the option Class Library (.NET Core) and click Next.
14
SpecFlow
To build this solution, go to the Build menu, then select Build Solution.
15
SpecFlow
Build success message gets displayed and we have successfully created a project in Visual
Studio.
16
5. SpecFlow - Visual Studio Extension Installation SpecFlow
As mentioned earlier, Visual Studio extension allows a lot of added features required
for test automation. This extension is available for Visual Studio 2017 and 2019.
Installation
Open Visual Studio and navigate to Extensions menu, then click on Manage Extensions
option.
Manage Extensions pop-up comes up. Type SpecFlow in the search box. Once the
search results get populated. Click on Download.
Once the download is completed, we need to restart Visual Studio. As the installation is
done, if we again go to the Manage Extensions pop-up, we can find this extension within
the Installed tab.
Also, we can find the options to Disable and Uninstall now for the SpecFlow. Click on
Close to exit.
17
SpecFlow
18
6. SpecFlow — Project Set Up SpecFlow
Now, we shall create a SpecFlow project within the same project we have built earlier.
Project Creation
Right-click on the Solution Explorer section. Click on the Add option. Then choose New
Project.
Type SpecFlow within the search box, SpecFlow Project gets displayed because of search
results. Click on Next to proceed.
19
SpecFlow
Enter the project name and location and then click on Create.
Select SpecFlow+ Runner option under the Test Framework dropdown from the
Create a new SpecFlow project pop-up. Then click on Create.
20
SpecFlow
The Solution Explorer shall now have a new project called the SpecFlowProject1 created.
Project Folder
As the SpecFlow project is created, we shall also find a well-defined folder structure
created for the project consisting of the Drivers, Dependencies, Features, Hooks, and so
on.
21
SpecFlow
22
7. SpecFlow — Other Project Dependencies SpecFlow
We need to have a project reference to the class library we have created for the SpecFlow
project. This is important for testing the class within the class library in the project.
The Reference Manager pop-up opens. Select the checkbox for the class library and then
click on OK.
23
SpecFlow
Navigate to the Tests menu and choose the Test Explorer option.
24
SpecFlow
We should be able to find the Features added to the SpecFlow project. Execute them via
the Run All Tests in View option. The status of the execution shows as Not Run as the
tests have still not been executed.
The exclamation symbol before a Feature suggests, test execution is pending for that
Feature.
25
8. SpecFlow — Runner Activation SpecFlow
We have to perform the activation of SpecFlow + Runner. Navigate to View menu, then
select the option Output.
We should obtain the test output along with the activation link of the runner. We should
have this link available only if we have chosen SpecFlow+ Runner at the time of project
set up.
26
SpecFlow
Activate Link
Open the activation link on a browser. We should get navigated to the SpecFlow landing
page. Click on Sign in with Microsoft.
27
SpecFlow
For setting up the account, provide the information needed. Then click on Create
Account.
28
SpecFlow
29
SpecFlow
Now, if we again execute the test from the Text Explorer, it will display the proper results.
30
9. SpecFlow — HTML Reports SpecFlow
SpecFlow generates reports when all your tests completed executing and which includes
breakdown of the test results.
Navigate to the Tests menu and choose the Test Explorer option.
31
SpecFlow
We should be able to find the Features added to the SpecFlow project. Execute that via
the Run All Tests in View option.
Report Generation
Go to the Output menu and select Tests from the Show output from: dropdown.
32
SpecFlow
The total execution results get displayed in the Output Console. It contains information
about the count of the test cases, total succeeded, ignored, skipped, failed, and so on. The
user and machine names where the execution happened are also captured.
Also, the execution duration is displayed along with the link to the HTML report and the
log file path.
Copy the Report file path and open it on the browser. We shall get a detailed HTML report
with the project name, configuration, execution start time, duration, number of threads,
and so on.
It shall describe the Results, Test Timeline Summary and the complete Feature Summary.
33
SpecFlow
The report also consists of the Error Summary and Scenario Summary as well. It contains
the Success Rate for each test. To know the details of a particular Feature, we can click
on the Scenario Name(provided as a link).
Next, the Execution Details are captured for every step. Each step details are displayed
with Trace and Result.
34
10. SpecFlow — Binding Test Steps SpecFlow
Visual Studio identifies the corresponding step definition to this step. In this example, it
opens the class CalculatorStepDefinitions and moves to the GivenTheFirstNumberIs
method.
35
SpecFlow
36
11. SpecFlow - Creating First Test SpecFlow
We shall now create a file in the class library which performs subtraction of two numbers.
using System;
namespace ClassLibrary2
{
public class Class1
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public int Subtraction()
{
return Number1 - Number2;
}
}
}
using ClassLibrary2;
using FluentAssertions;
using [Link];
namespace [Link]
{
37
SpecFlow
[Binding]
public sealed class CalculatorStepDefinitions
{
private readonly ScenarioContext _scenarioContext;
//instantiating Class1
private readonly Class1 _calculator = new Class1();
private int _result;
public CalculatorStepDefinitions(ScenarioContext scenarioContext)
{
_scenarioContext = scenarioContext;
}
[Given("the first number is (.*)")]
public void GivenTheFirstNumberIs(int number)
{
_calculator.Number1 = number;
}
[Given("the second number is (.*)")]
public void GivenTheSecondNumberIs(int number)
{
_calculator.Number2 = number;
}
[When("the two numbers are subtracted")]
public void WhenTheTwoNumbersAreSubtracted()
{
_result = _calculator.Subtraction();
}
[Then("the result should be (.*)")]
public void ThenTheResultShouldBe(int result)
{
_result.Should().Be(result);
}
}
}
38
SpecFlow
Select the SpecFlowProject1 feature and click on Run All tests in View.
The result shows as 1 Passed along with execution duration. Click on the option Open
additional output for this result to get result details.
All the steps in the Feature File get executed along with status as done. Also, the
corresponding methods in the Step Definition File get displayed with the execution
duration.
39
12. SpecFlow — Configure Selenium Webdriver SpecFlow
To configure Selenium Webdriver in Visual Studio, we shall take the help of NUnit
framework. This framework allows to run Selenium tests in C#.
Once the Visual Studio landing page gets opened, click on Create a new project.
Type NUnit in the search box appearing in Create a new project pop-up. Select NUnit
Test Project(.NET Core) from the search results. Click on Next.
40
SpecFlow
As the project is set up on NUnit(.Net Core), the Setup and Test methods shall be defined
by default. Also, the statement using [Link] should reflect at the top. This
shall prove that NUnit Framework has been successfully configured.
41
SpecFlow
We must execute the required Package Manager commands for installation of Selenium
Webdriver and NUnit.
42
SpecFlow
For Selenium installation, run the below commands in Package Manager Console:
Install-Package [Link]
Install-Package [Link]
For NUnit installation, run the below commands in Package Manager Console:
Install-Package NUnit
Install-Package UUnit3TestAdapter
To check the installation status, run the command in Package Manager Console:
Get-Package
Click on Open additional output for this result link, we should get the Test Outcome
and Standard Output.
44
13. SpecFlow — Gherkin SpecFlow
Rules in Gherkin
Some of the rules in Gherkin are listed below:
Comments can be added at the beginning of the new line in the Feature File. They
start with or without spaces followed by # symbol and text. However, block
comments cannot be added till now in SpecFlow.
To indent the code, spaces or tabs can be used. It is recommended to have two
spaces for indentation.
The content after the keyword for each step has a corresponding block of code.
This is known as the Step Definition.
Gherkin Example
Following is the Gherkin example:
# Example 1
Scenario: Member Payment Method
When a member is on Payment screen
Then the payment amount is displayed.
# Example 2
Scenario: Member Payment Dues
When a member is on Payment Due screen
Then the payable amount is displayed.
In the above example, Feature, Scenario, Given, When, and Then are known as the
Gherkin keywords.
45
14. SpecFlow — Gherkin Keywords SpecFlow
Feature
Scenario
Rule(till Gherkin 6)
Example or Scenario
Background
Scenario Outline
Examples
| for Data table
""" for Document Strings
@ for Tags
# for Comments
Given
When
Then
But
And
Gherkin uses localization for multiple languages and each of the above keywords has its
equivalent terms in respective languages.
Feature
A Feature is added to have an overall description of the features of the applications
and to club connected scenarios. This is the most important keyword in a Gherkin
document.
A Feature is followed by a colon: symbol and then a small description on the feature. We
can add multiple lines for more description. These are not considered by SpecFlow at
execution but are added in the html reports.
46
SpecFlow
Once the description of a Feature is completed, we should begin a new line with keywords
Background, Example, and so on. We can add tags above Feature to club similar features,
irrespective of the structure of file or directory.
Tags
Tags are markers added to Scenarios or Features. Giving a tag to a Feature is like marking
that tag to every Scenario within that Feature file. A tag name is mentioned after the @
symbol.
We can filter and club tests to be run with the tags. For instance, we can tag an urgent
test with @important and run it quite often. SpecFlow considers the @ignore tag as an
important one and produces an ignored unit test method out of the Scenarios with this
tag.
47
SpecFlow
Here, the Feature File contains two scenarios with @Calculator tag. The same shall also
be reflected in the Test Explorer, to pick and choose the test to be run.
48
SpecFlow
Scenario
Scenario is a complete instance that describes a business logic. It has multiple steps. It is
often considered a synonym of keyword Example. A Scenario does not have a fixed
number of steps. But it is recommended to have 3 to 5 steps per Scenario.
If there are too many steps, it may lose its value to be used as specification and
documentation. A Scenario is like a test in a development lifecycle. Also, it can be divided
into a precondition, test step and verification.
Given
Given are steps used for describing the pre-existing condition of the system. It typically
deals with the events that have occurred in the past. As a Given step is executed, it shall
set the objects, test data in the database and put the system in a proper state.
Thus, the Given step helps to define the system in a known condition prior to the
interaction of the user with the system. We can have multiple Given steps. Two or more
Given steps can be used with And keyword. In short, it is used to have the preconditions
defined.
49
SpecFlow
When
When is a step used for describing an action or an incident. This can either be an
interaction of the person with the system or an incident caused by another system. It is a
good practise to have a single When step in a Scenario.
If we are forced to have multiple When steps, we should ideally break the Scenario into
smaller ones.
Then
Then is a step used for describing an expected result. The corresponding step definition of
a Then step should have an assertion to verify actual result against the expected result.
Thus, it basically deals with the output obtained from the tests (message, report, and so
on) and not on the internal characteristics of the system, for instance a database record.
In other words, it is used for an outcome that is noticeable from the end user perspective.
But, And
If we have repeated Given, When and Then steps, then we can make the Scenarios more
organized by replacing the consecutive Given, When, Then steps with And, But steps.
50
SpecFlow
The * symbol
The * symbol is used in place of another step keyword. This can be used for steps that
represent a list of items. It is more like a bullet point. For the below example, two And
steps have appeared one after the other.
Background
Sometimes, we may require repeating the same steps for all Scenarios within the Feature
file. We may shift these steps to the backdrop by clubbing them under the Background
segment.
51
SpecFlow
It helps to add context to a scenario. It can have more than one Given step. Thus, it shall
execute prior to execution of each Scenario, but post any Before hooks.
A Background is kept prior to the first Example or Scenario, at the similar indentation
level. In short, Background is used for declaring the common steps to all the tests.
In the above example, having two Scenarios, the Background steps shall run once before
execution of each of these scenarios.
Scenario Outline
Scenario Outline is used to replicate the same Scenario with a different data set. Writing
the same tests with different values is cumbersome and time taking. For instance,
We can club the above two scenarios with the Scenario Outline.
52
SpecFlow
Thus, we see that a Scenario Outline should be accompanied with keyword Examples. A
Scenario Outline is executed once for each of the rows appearing below the Examples
segment.
Also, we have seen that the Given step has the <> delimiter. It points to the header of
the Examples table. SpecFlow shall put the values within this table prior to the task of
matching a step with a Step Definition.
Data Table
Data Table is used to send a group of values in the form of a list to the Step Definition
file. It is useful to deal with large data sets. SpecFlow has a rich API for table manipulation
in the Step Definition File.
SpecFlow Assist Helpers packages are used to work on tables. Also, we have to add
namespace [Link] to our code.
53
15. SpecFlow — Feature File SpecFlow
The SpecFlow test execution begins from the Feature File. Here all the Features and their
corresponding Scenarios are explained in plain text. It has a dual role of serving as an
automation element as well as for documentation. A Feature File consists of one or more
Scenarios in form of a list. The extension for a Feature File should always be .feature.
A Feature is followed by a colon: symbol and then a small description on the feature. We
can add multiple lines for more description. These are not considered by SpecFlow at
execution but are added in the html reports.
Once the description of a Feature is completed, we should begin a new line with keywords
Background, Example, and so on. We can add tags above Feature to club similar features,
irrespective of the structure of file or directory.
54
SpecFlow
Right-click on Features folder. Click on Add, then select the option New Item.
Add New Item pop-up comes up. Type SpecFlow Feature in the search box. Select the
option SpecFlow Feature File from the search results. Click on Add and proceed.
55
SpecFlow
The Feature File gets generated with few steps created by SpecFlow by default.
56
SpecFlow
A Feature File is mainly composed of the Gherkin Keywords to take a form of a Feature
having one or multiple Scenarios.
57
16. SpecFlow — Step Definition File SpecFlow
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.
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.
It should be public.
The details of how to create a Feature File is discussed in detail in the Chapter – Feature
File.
58
SpecFlow
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.
Give the location of saving the Step Definition File and then click on Save.
59
SpecFlow
The Step Definition File gets opened with for all the matching steps in the Feature File. It
also contains regular expression attributes.
60
SpecFlow
61
SpecFlow
62
17. SpecFlow — Hooks SpecFlow
Hooks are event bindings to add more automation logic at certain steps. For example, for
any step which is needed to be run prior to a specific Scenario. To introduce, hooks in the
code we have to add the [Binding] attribute.
Hooks have global access. But it can be made available to a Features and Scenarios by
declaring a scoped binding. The scoped binding can be filtered with the tags.
Hook Attributes
The Hook attributes are listed below:
Example
[AfterScenario(Order = 1)]
public void CloseBrowser()
{
// we require this method to execute first...
}
[AfterScenario(Order = 2)]
63
SpecFlow
The number signifies order which means that the hook with the lowest number is run first.
If the number is omitted, the default value is 10000. It is not a good practise to depend
on it and rather mention the order for individual hooks.
Also, if an unhandled exception is thrown, all the following hooks of similar type will be
skipped. In order to prevent that, we should handle all the exceptions.
64
18. SpecFlow — Background Illustration SpecFlow
Background keyword is applied to replicate the same steps before all Scenarios within a
Feature File. We may shift these steps to the backdrop by clubbing them under the
Background segment.
It helps to add context to a scenario. It can have more than one Given step. Thus, it shall
execute prior to execution of each Scenario, but post any Before hooks.
A Background is kept prior to the first Example or Scenario, at the similar indentation
level. In short, it is used for declaring the common steps to all the tests.
In the above example, having two Scenarios, the Background steps shall run once before
execution of each of these scenarios.
Background Rules
Let us describe some of the rules while applying Background:
It should be used for defining simple steps unless we are forced to bring the
application to a state which requires complicated steps to be carried out. As
requested by the stakeholders of the project.
Background Example
65
SpecFlow
Let us see an example where we have used Background steps to be executed before all
the tests in the Feature File. For instance, to add a normal and admin user for an
application, we require the below steps to be run before the execution of the Scenario
Normal user addition:
Background:
Given launch URL
Then enter name and password
using System;
using [Link];
namespace [Link]
{
[Binding]
public class MemberAdditionSteps
{
[Given(@"launch URL")]
public void GivenLaunchURL()
66
SpecFlow
{
[Link]("Url launched");
}
[Given(@"user is on normal user additon screeen")]
public void GivenUserIsOnNormalUserAdditonScreeen()
{
[Link]("User is on normal user addition screen");
}
[Given(@"user is on admin user addition screen")]
public void GivenUserIsOnAdminUserAdditionScreen()
{
[Link]("User is on admin user addition screen");
}
[When(@"enters normal user details")]
public void WhenEntersNormalUserDetails()
{
[Link]("User enters normal user details");
}
[When(@"enters admin user details")]
public void WhenEntersAdminUserDetails()
{
[Link]("User enters admin user details");
}
[Then(@"enter name and password")]
public void ThenEnterNameAndPassword()
{
[Link]("User enters name and password");
}
[Then(@"user should be added as normal user")]
public void ThenUserShouldBeAddedAsNormalUser()
{
[Link]("User should be added as normal user");
}
[Then(@"user should be added as admin user")]
public void ThenUserShouldBeAddedAsAdminUser()
{
[Link]("User should be added as admin user");
67
SpecFlow
}
}
}
Select Normal user addition Scenario, then click on Open additional output for this
result link.
68
SpecFlow
In the above output, the Background steps - Given Url launched and Then enter name
and password got executed prior to the actual normal user Scenario.
Select Admin user addition Feature, then click on Open additional output for this
result link.
69
SpecFlow
In the above output as well, the Background steps - Given Url launched and Then enter
name and password got executed prior to the actual admin user Scenario.
70
19. SpecFlow — Data Driven Testing with SpecFlow
Examples
We can perform data driven testing with the help of keyword Examples. We shall also
take the help of keyword Scenario Outline to execute the same Scenario over multiple
values.
The data sets to be taken into consideration shall be passed below the Examples section
one after another separated by | symbol. So, if there are three rows, we shall have three
test cases executed from a Single scenario.
Scenario Outline is used to replicate the same Scenario with a different data set. Writing
the same tests with different values is cumbersome and time taking. For instance,
We can club the above two scenarios with the Scenario Outline.
Thus, we see that a Scenario Outline should be accompanied with keyword Examples. A
Scenario Outline is executed once for each of the rows appearing below the Examples
segment.
Also, we have seen that the Given step has the <> delimiter. It points to the header of
the Examples table. SpecFlow shall put the values within this table prior to the task of
matching a step with a Step Definition.
71
SpecFlow
Examples:
| username | password |
| tutorialspoint1| pwd |
| tutorialspoint2| pwd1 |
using System;
using [Link];
namespace [Link]
{
[Binding]
public class UserCredentialSteps
{
//regular expression used to point to data
[Given(@"user types (.*) and (.*)")]
public void GivenUserTypesUserAndPwds(string username, string password)
{
[Link](username);
[Link](password);
}
[Then(@"user should be able to login")]
public void ThenUserShouldBeAbleToLogin()
72
SpecFlow
{
[Link]("User should be able to login");
}
}
}
Select Login module, tutorialspoint1 Scenario, then click on Open additional output for this
result link.
The Scenario got executed with username – tutorialspoint1 and password – pwd as
specified in Examples(1st row).
Select Login module, tutorialspoint2 scenario, then click on Open additional output for this
result link.
73
SpecFlow
The test got executed with username – tutorialspoint2 and password – pwd1 as
specified in Examples(2nd row).
74
20. SpecFlow — Data Driven Testing without SpecFlow
Examples
We can perform data driven testing without the help of keyword Examples. This can be
done by passing the data directly to the steps within the Feature File enclosed in (''). It
will then be provided as an input to the Step Definition File.
Let us verify a module, for which the below steps need to be executed:
using System;
using [Link];
namespace [Link]
{
[Binding]
public class LaunchingApplicationSteps
{
[Given(@"User hits URL '(.*)'")]
public void GivenUserHitsURL(string url)
{
[Link](url);
}
[Then(@"URL should be launched")]
public void ThenURLShouldBeLaunched()
75
SpecFlow
{
[Link]("URL should be launched");
}
}
}
Select Launch URL Scenario, then click on Open additional output for this result link.
76
21. SpecFlow — Table conversion to Data Table SpecFlow
A Table is often confused with a Scenario Outline. While a Scenario Outline is applicable
for the complete test, a Table is only for a single step under which it is defined.
However, a programming logic needs to be built to comprehend the data and then it can
be incorporated in our test. An Examples keyword is used for a Scenario Outline, but no
keywords are required for Data Table.
There are multiple methods available in Table in SpecFlow, let us see how to convert a
Table to Table via Table headers.
Table is used to send a group of values in the form of a list to the Step Definition file. It
is useful to deal with large data sets. SpecFlow has a rich API for table manipulation in the
Step Definition File.
SpecFlow Assist Helpers packages are used to work on tables. Also, we have to add
namespace [Link] to our code.
77
SpecFlow
Right-click on the new Folder created, then select the option Add. Click on Class.
78
SpecFlow
Type C# Class in the search box and search. Select the option Class from the search
result and then click on Add to proceed.
79
SpecFlow
C# Class Implementation
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace [Link]
{
class Class1
{
public static DataTable DT(Table t)
{
var dT = new DataTable();
foreach (var h in [Link])
{
[Link](h, typeof(string));
}
// iterating rows
foreach (var row in [Link])
{
var n = [Link]();
foreach (var h in [Link])
{
80
SpecFlow
[Link](h, row[h]);
}
[Link](n);
}
return dT;
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace [Link]
{
[Binding]
public class UserCredentialSteps
{
[When(@"User types details")]
public void WhenUserTypesDetails(Table t)
{
//Accessing C# class method from Step Definition
var dTable = [Link](t);
//iterating rows
foreach (DataRow r in [Link])
{
[Link]([Link][0].ToString());
[Link]([Link][1].ToString());
}
}
[Then(@"user should be able to login")]
public void ThenUserShouldBeAbleToLogin()
{
[Link]("User should be able to login");
81
SpecFlow
}
}
}
Select Login Module Scenario, then click on Open additional output for this result
link.
82
SpecFlow
The Scenario got executed with data passed from a Table (converted to a Data Table) in
the Feature File within the When step.
83
22. SpecFlow — Table conversion to Dictionary SpecFlow
Tables can hold data in a horizontal and vertical direction in the Feature File. With a
Dictionary object, we shall see how to access data in the Feature File vertically in a key-
value pair.
84
SpecFlow
Right-click on the new Folder created, then select the option Add. Click on Class.
85
SpecFlow
C# Class Implementation
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace [Link]
{
class Class1
{
public static Dictionary<string, string> ToDT(Table t)
{
var dT = new Dictionary<string, string>();
// iterating through rows
foreach (var r in [Link])
{
[Link](r[0], r[1]);
}
return dT;
}
}
}
86
SpecFlow
using System;
using [Link];
namespace [Link]
{
[Binding]
public class UserCredentialSteps
{
[When(@"User types details")]
public void WhenUserTypesDetails(Table t)
{
//Accessing C# class method from Step Definition
var dict = [Link](t);
[Link](dict["username"]);
[Link](dict["password"]);
}
[Then(@"user should be able to login")]
public void ThenUserShouldBeAbleToLogin()
{
[Link]("User should be able to login");
}
}
}
Select Login Module Scenario, then click on Open additional output for this result
link.
87
SpecFlow
The Scenario got executed with data passed from a Table (converted to a Dictionary) in
the Feature File within the When step.
88
23. SpecFlow — Table with CreateInstance SpecFlow
The SpecFlow Assist Helpers package is used to work on tables. Also, we have to add
namespace [Link] 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.
89
SpecFlow
Right-click on the new Folder created, then select the option Add. Click on Class.
Type C# Class in the search box and search. Select the option Class from the search
result and then click on Add to proceed.
90
SpecFlow
C# Class Implementation
using System;
using [Link];
using [Link];
namespace [Link]
{
class Class1
{
public class Input
{
//Declaring string objects
public string Input1 { get; set; }
public string Input2 { get; set; }
}
}
}
91
SpecFlow
using System;
using [Link];
using [Link];
namespace [Link]
{
[Binding]
public class UserCredentialSteps
{
[When(@"User types details")]
public void WhenUserTypesDetails(Table t)
{
//access data with CreateInstance method using C# class
method
var i = [Link]<[Link]>();
[Link](i.Input1);
[Link](i.Input2);
}
[Then(@"user should be able to login")]
public void ThenUserShouldBeAbleToLogin()
{
[Link]("User should be able to login");
}
}
}
92
SpecFlow
Select Login Module Scenario, then click on Open additional output for this result
link.
The Scenario got executed with data passed from a Table in the feature file within the
When step using CreateInstance method.
93
24. SpecFlow — Table with CreateSet SpecFlow
CreateSet<T> is an extension of the Table method. It transforms the data in the Table
to a group of objects. It is one of the popular techniques to have parameterization of data
in a horizontal alignment.
We can handle one or many rows of data with this method. The SpecFlow Assist Helpers
package is used to work on tables. Also, we have to add namespace
[Link] to our code.
94
SpecFlow
Right-click on the new Folder created, then select the option Add. Click on Class.
Type C# Class in the search box and search. Select the option Class from the search
result and then click on Add to proceed.
95
SpecFlow
C# Class Implementation
using System;
using [Link];
using [Link];
namespace [Link]
{
class Class1
{
public class Input
{
//two string objects declared
public string Input1 { get; set; }
public string Input2 { get; set; }
}
}
}
The details of how to create a Step Definition File is discussed in detail in the Chapter –
Step Definition File.
using System;
using [Link];
using [Link];
namespace [Link]
{
[Binding]
public class UserCredentialSteps
{
[When(@"User types details")]
public void WhenUserTypesDetails(Table t)
{
//access Table data with CreateSet method
var i = [Link]<[Link]>();
//iterate over rows
foreach (var r in i)
{
[Link](r.Input1);
[Link](r.Input2);
}
}
[Then(@"user should be able to login")]
public void ThenUserShouldBeAbleToLogin()
{
[Link]("User should be able to login");
}
}
}
97
SpecFlow
Select Login Module Scenario, then click on Open additional output for this result
link.
The scenario got executed with data passed from a Table in the feature file within the
When step using CreateSet method.
98