The entire cycle of software design, development, and testing are pretty complicated. Each team works towards a common goal. BDD plays an instrumental role as it minimizes the communication gap between the key stakeholders of any software project. This SpecFlow tutorial will help you understand how BDD can be utilized.
In the.NET framework, Specflow is a testing framework that supports BDD (Behavior-Driven Development) approaches. It's a GitHub-hosted open-source framework. It facilitates the creation of acceptance test drivers for .NET applications utilizing ATDD (Acceptance test driver development). This allows us to create scenarios in plain English using the Gherkin language, which is easily understood by everyone.
BDD concepts are supported by Spec Flow. It makes writing acceptance test drivers for .NET applications that use ATDD (Acceptance test driver development). Using the Gherkin language, we can build situations in simple English that anybody can understand. This introductory SpecFlow tutorial will cover everything you need to know about.
We will use SpecFlow as the BDD interpreter in this SpecFlow tutorial for utilizing SpecFlow Selenium C#. Following the parsing of the feature film, the automation code for that Scenario is invoked.
Automation Tests include NUnit framework + Selenium WebDriver
This section provides the test code for each Scenario. In the file where the automation tests are implemented, each scenario step will have a matching Step definition. Each Step definition, in turn, will have a method/code implementation to which it will be tied. Because there is a connection between the Scenario Steps -> Step Definition -> Methods, it is also known as Code Binding.
We'll utilize the NUnit test framework with the Selenium test suite for this SpecFlow lesson, which employs the Selenium WebDriver to interact with the underlying parts of a web page.
If you want to enrich your career and become a professional in SpecFlow, then enroll in "SpecFlow Training". This course will help you to achieve excellence in this domain. |
In this SpecFlow tutorial, we utilize Visual Studio 2019 as the IDE to demonstrate SpecFlow Selenium C# and the NUnit framework. For conducting operations on the respective web components presented on the web page, Selenium leverages the Selenium WebDriver. You should have the Selenium WebDriver installed on your workstation for local Selenium testing.
The installation of Specflow is a two-step procedure.
1) Using the Visual Studio IDE to install the essential plugins.
2) Creating feature files and step definitions for the project.
3) Make a new class called "CalculatorApplication" that will serve as our test application. This is a basic class including functions for doing addition, multiplication, division, square root, and other operations on the provided input. The CalculatorApplication class looks like this.
4) After installing the package, create two folders in the project and call them Features and Step Definitions, respectively, to store the feature files and step bindings. The reason for this folder arrangement for Feature & Step definitions will be discussed in depth.
5) Create a new Feature file in the features folder and call it CalculatorFeature.
You would see that by default, the feature file has some description in Feature and Scenario.
You would see that by default, the feature file has some description in Feature and Scenario.
Replace that with what we are going to test.
Feature: CalculatorFeature
In order to test my application
As a developer
I want to validate different operations of the application
Scenario: Add two numbers
Given I have provided 50 and 20 as the inputs
When I press add
Then the result should be 70
Scenario: Subtract two numbers
Given I have provided 50 and 20 as the inputs
When I press subtract
Then the result should be 30
Scenario: Multiply two numbers
Given I have provided 50 and 20 as the inputs
When I press multiply
Then the result should be 1000
Scenario: Divide two numbers
Given I have provided 50 and 20 as the inputs
When I press divide
Then the result should be 2.5
Scenario: SquareRoot of number
Given I have provided 50 as input
When I press square root
Then the result should be 3.87
6) Creating Step Definitions: Specflow allows you to construct bindings/implementation for the various stages in feature file scenarios in an automated manner. By right-clicking on the feature file and selecting "Generate Step Definitions," you may accomplish this.
This phase does not ensure that all of the steps will be implemented, but it does its best to combine common steps into scenarios and reuse as many bindings as possible. However, when a scenario step needs to be created, it makes the work of avoiding boilerplate code easier.
After selecting "Generate Step Definitions," a window will appear with a list of the processor's discovered step implementations. As needed, one can pick or de-select the options.
In the following sections, we'll go deeper into the Style option seen in the picture above.
Let's keep all of them chosen with default settings for the time being. When you click on the Preview button, you'll see a preview of how the implementation will appear.
If there are still any unimplemented steps after developing Step definitions, the Feature files give a visual manner of identifying the unimplemented applications. It highlights such actions in a distinct color, making it very clear that there are specific steps that have yet to be implemented.
Note: Step definitions can also be produced manually — any .cs file with the [Binding] Attribute is a Step implementation class. The Gherkin syntax will check for a match for the specified scenario step implementation.
It is used with the Visual Studio IDE or via the command prompt. The most current version of SpecFlow used to create this SpecFlow instructional was 3.0.225. SpecFlow also supports MSTest v2, xUnit 2, and other essential test frameworks in addition to NUnit. We recommend reading the NUnit test automation guide for more details on the framework.
Selenium is a free (open-source) automation framework for web applications that work with many browsers and operating systems; further information is available here. It's typically used in conjunction with SpecFlow to assess the user interface of your web project.
In this SpecFlow tutorial, we utilize Visual Studio 2019 as the IDE to demonstrate SpecFlow Selenium C# and the NUnit framework.
For conducting operations on the respective web components presented on the web page, Selenium leverages the Selenium WebDriver. You should have the Selenium WebDriver installed on your workstation for local Selenium testing. For common browsers such as Opera, Firefox, Chrome, Internet Explorer, Microsoft Edge, and others, Selenium WebDriver is available.
Note: If you're still using previous versions of Visual Studio, such as Visual Studio 2015/Visual Studio 2017, the installation process for SpecFlow Selenium C# may differ somewhat.
You must first install SpecFlow integration for Visual Studio 2019 before beginning the SpecFlow lesson.
You have two options for installing this plugin:
Manage Extensions — The Manage Extensions option in the IDE is the second way to add SpecFlow integration for Visual Studio 2019.
Plugin Installation instructions
We'll develop a "Class Library" project to demonstrate how to use SpecFlow with the NUnit framework.
4.5.2 of the Net Framework.
We install SpecFlow, SpecFlow.NUnit, and SpecFlow.Tools after the project are set up. MsBuild.Generation is a collection of MSBuild. Generation packages. We need to install the SpecFlow.NUnit package since we're utilizing the NUnit test framework with SpecFlow Selenium C#. SpecFlow.Tools. In SpecFlow 3, the MsBuild.A generation package is required to build code-behind-the-files.
These packages can be downloaded using two methods
Execution of the commands on the Package Manager (PM) Console could be
The installation screenshots are shown below:
By executing the command Get-package on the Packet Manager Console, one can check whether the packages are installed or not. Shown below is the command execution output:
PM> Get-Package ID | Versions |
SpecFlow | {3.0.225} |
SpecFlow.NUnit | {3.0.225} |
SpecFlow.Tools.MsBuild.Generation | {3.0.225} |
Install-Package NUnit3TestAdapter | {3.15.1} |
NuGet Package Manager – for opening the NuGet Package Manager, go to ‘Tools’ -> ‘NuGet Package Manager’ -> ‘Manage NuGet Packages for Solution
Search for the SpecFlow package in the Browse area and install it. Next, look for SpecFlow.NUnit package and install it. The current stable version of the SpecFlow, SpecFlow.NUnit, and SpecFlow.Tools.MsBuild.Generation packages were 3.0.225 at the time of creating this SpecFlow lesson.
NUnit3TestAdapter was version 3.15.1 at the time.
SpecFlow and SpecFlow.NUnit is the base package required for any type of C# project on SpecFlow and NUnit test framework.
Data-Driven Testing is a software testing method in which test data is stored in a table or spreadsheet format. Data-driven Testing allows testers to write a single test script that runs tests for all test data from a database and expects the test results to be provided in the same table. It's also referred to as Table-Driven Testing or parameterized testing.
Tables in Specflow are quite useful and may be utilized in various ways. Tables may also be used to manage enormous amounts of information. They're strong but not intuitive because you have to deal with dictionary objects, simple class objects, and collections.
Tables are part of the SpecFlow Assist Helpers package. We'll need to add TechTalk.SpecFlow.Assist the namespace at the top of your code to utilize these aids.
The [Binding] characteristic is the essential component.
The [Binding] attribute is adequate to guarantee the runner finds our CommonStepDefinitions class when it initializes, so we don't need to give it a specific name.
This may be what you're looking for, but it's also possible that it isn't. Limiting the scope using [Scope] properties is possible; however, utilizing them in the CommonStepDefinitions class would be counter-intuitive. Reverting to [Scope] is also considered an anti-pattern;
Any step definition — Given, When, Then — may be added to the CommonStepDefinitions class; for example, the example above contains a common step that I've included in almost every SpecFlow project.
The usage of attributes like [BeforeScenario] in the CommonStepDefinitions class should be carefully considered before implementation (and much more so if the [BeforeFeature] / [BeforeTestRun] details are used), but they may be pretty beneficial.
Multiple Characteristics: Another option to share steps is to add multiple bindings to the function you wish to share, either within the CommonStepDefinitions class (or any specialized feature file for that matter):
Related Article: SpecFlow Interview Questions |
TDD's cousin, Behavior Driven Development (BDD), is a kind of extension of TDD (Test Driven Development).TDD is a programming technique in which programmers only write code after the automated tests have failed. BDD is all about having talks and discussions across the project's many teams so that everyone understands the feature needs. Once development begins, they can collaborate toward a unified objective of identifying user stories.
The heart and soul of the BDD method is 'conversation,' and anything beyond that is optional. The main distinction between BDD and ATDD (Acceptance Test Driven Development) is that the focus is now on "behavior" rather than "test." In this SpecFlow lesson, we'll try to comprehend it better. Development from the Outside-In,
The acceptance tests in BDD, are created from the outside, focusing on business behavior rather than technical implementation. The benefit of this kind of development is that the language employed is common in nature and can be easily comprehended by both technical and non-technical persons. The outside-in product integrates the best of both worlds, TDD and ATDD, into a single methodology.
The 'User Stories' are at the heart of the BDD process, and developers must first compose them. These user stories document the functionality, trigger acceptance tests, and automate them. As a result, BDD is ideal for Acceptance Tests.
Scenarios are the word used in BDD to describe examples. A scenario describes how a feature should operate when various types/values of input parameters are used. Scenarios are written in the Gherkin format. Gherkin is a domain-specific language that allows you to create scenarios that explain business behavior without worrying about technical details.
Because BDD is a crucial component of this SpecFlow lesson; one should know its benefits. The following are the benefits of utilizing BDD:
The following are significant characteristics of BDD:
It uses an example or Scenario to characterize the system or feature being created. For example, if you're making a basic Calculator App, the many behaviors include addition, multiplication, division, and so on.
As a result of BDD, all stakeholders will first gather to decide on the application's behavior. Such as Addition, and will have situations similar to those described below.
I'm given two numbers to work with: 30 and 50. When I add these two integers together, I get
Then I should get an output of 80.
If you look at the illustration above, it's a scenario written in plain English that everyone can understand and clarifies the needs for a product (as per the acceptance criteria). As a result, the first step is to identify these needs.
As a result, BDD takes the TDD technique to the next level by incorporating standard, readily understood specifications in scenarios. They are also the feature documentation in and of themselves.
Cucumber/JBehave for Java, Lettuce for Python, Jasmine for Javascript, and Specflow for .NET are tools for developing tests in the BDD methodology.
Most of us know the 3 A's, which stand for Arrange, Act, and Assert in unit testing. In the BDD universe, they are replaced by Now, Given, When, and Then.
Assume you're creating a scenario for validating a product added to an e-commerce application's shopping cart that requires you to be logged in as a prerequisite.
The following is an example of a specification:
The feature file is simply a collection of different situations for the program being developed or tested. It may also be regarded as multiple application modules that can be logically isolated from one another.
Cucumber is a program that reads plain text Gherkin syntax specification files and executes those specs using ruby files. Specflow is a cucumber. Net 'port' that uses Gherkin syntax files but connects them to. Net code.
Related Article: SpecFlow vs Cucumber |
The code files used in the application are shown below:
CalculatorFeatureSteps.cs
using System;
using TechTalk.SpecFlow;
using NUnit;
using NUnit.Framework;
namespace SpecflowBasic.StepDefinitions
{
[Binding]
public class CalculatorFeatureSteps
{
// instantiating application instance
CalculatorApplication app = new CalculatorApplication();
// variables to hold input values and the intermediate result
int input1, input2;
double output;
[Given(@"I have provided (.*) and (.*) as the inputs")]
public void GivenIHaveProvidedAndAsTheInputs(int p0, int p1)
{
input1 = p0;
input2 = p1;
}
[Given(@"I have provided (.*) as input")]
public void GivenIHaveProvidedAsInput(int p0)
{
input1 = p0;
}
[When(@"I press add")]
public void WhenIPressAdd()
{
output = app.add(input1, input2);
}
[When(@"I press substract")]
public void WhenIPressSubstract()
{
output = app.subsctract(input1, input2);
}
[When(@"I press multiply")]
public void WhenIPressMultiply()
{
output = app.multiply(input1, input2);
}
[When(@"I press divide")]
public void WhenIPressDivide()
{
output = app.divide(input1, input2);
}
[When(@"I press squareroot")]
public void WhenIPressSquareroot()
{
output = app.squareRoot(input1);
}
[Then(@"the result should be (.*)")]
public void ThenTheResultShouldBe(double p0)
{
Assert.AreEqual(p0, output);
}
}
}
CalculatorApplication.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpecflowBasic
{
class CalculatorApplication
{
public int add(int input1, int input2)
{
return input1 + input2;
}
public int subsctract(int input1, int input2)
{
return input1 - input2;
}
public int multiply(int input1, int input2)
{
return input1 * input2;
}
public double divide(double input1, double input2)
{
return input2 != 0 ? Math.Round(input1 / input2, 2) : 0;
}
public double squareRoot(int input1)
{
return input1 != 0 ? Math.Round(Math.Sqrt(input1), 2) : 0;
}
}
}
packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net461" />
<package id="NUnit" version="3.11.0" targetFramework="net461" />
<package id="SpecFlow" version="2.4.0" targetFramework="net461" />
<package id="SpecRun.Runner" version="1.8.5" targetFramework="net461" />
<package id="SpecRun.SpecFlow" version="1.8.5" targetFramework="net461" />
<package id="SpecRun.SpecFlow.2-4-0" version="1.8.5" targetFramework="net461" />
<package id="System.ValueTuple" version="4.3.0" targetFramework="net461" />
</packages>
For the.Net framework, SpecFlow is an open-source version of Cucumber. BDD tests may be produced using the Gherkin language and performed using the NUnit test framework utilizing SpecFlow with Selenium C#. It's also compatible with MSTest, xUnit, and other test frameworks. Features and Scenarios are stored in feature files, which are essential text files. Feature files do not require any technical knowledge because Gherkin is utilized in this SpecFlow course.
Automation testing using Selenium Grid has scalability concerns; hence remote Selenium Grid is advised for better test coverage. Existing tests may be converted to a more scalable Remote Selenium Grid by making minor modifications to the existing local Selenium WebDriver implementation. I hope this SpecFlow lesson helped you understand how to use SpecFlow with Selenium and C#.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
SpecFlow Training | Nov 19 to Dec 04 | View Details |
SpecFlow Training | Nov 23 to Dec 08 | View Details |
SpecFlow Training | Nov 26 to Dec 11 | View Details |
SpecFlow Training | Nov 30 to Dec 15 | View Details |
Usha Sri Mendi is a Senior Content writer with more than three years of experience in writing for Mindmajix on various IT platforms such as Tableau, Linux, and Cloud Computing. She spends her precious time on researching various technologies, and startups. Reach out to her via LinkedIn and Twitter.