Home > Agile, BDD, C#, Selenium, TDD, Test Automation > Behaviour Driven Development (BDD) in .Net using SpecFlow, Selenium and NUnit

Behaviour Driven Development (BDD) in .Net using SpecFlow, Selenium and NUnit

I have been working on the Behaviour Driven Development (BDD) using SpecFlow for .Net and I felt it is fun. According to me, it is a Tester’s tool rather than a Developer’s tool and I felt it is worth sharing. Kindly refer the wiki for more theoretical info on BDD: http://en.wikipedia.org/wiki/Behavior_Driven_Development

SOFTWARE REQUIREMENTS:

  • Windows 7 as OS
  • Microsoft Visual Studio 2010 as IDE
  • SpecFlow as BDD tool for .Net
  • NUnit as Unit Testing Tool
  • Selenium as a Test Automation Tool

SET-UP INSTRUCTIONS:

To install the Selenium WebDriver project:
  • Create a new Project with C# Class Library and save it (‘SpecflowTest‘ in my example).
  • Download and install NuGet Package Manager using Tools -> Extension Manager. Restart MS Visual Studio in order for the changes to take effect.
  • Go to Package Manager Console install the latest version of Selenium WebDriver by running the command Install-Package Selenium.WebDriver -Version 2.20.0
  • Install the latest version of Selenium WebDriver Support Classes by running the command Install-Package Selenium.Support
 
Referencing the NUnit Library:
  • Download the latest NUnit framework from the site: http://www.nunit.org
  • Install the NUnit software on your machine.
  • In Visual Studio, Go to the Project -> Add Reference menu item.
  • When the Add Reference dialog appears, click on ‘Browse‘ and navigate to C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0\framework and select nunit.framework.dll.
Referencing the SpecFlow:
  • Download the latest NUnit framework from the site: http://www.specflow.org/
  • Install the SpecFlow software on your machine.
  • In Visual Studio, Go to the Project -> Add Reference menu item.
  • When the Add Reference dialog appears, click on ‘Browse‘ and navigate to C:\Program Files (x86)\TechTalk\SpecFlow and select TechTalk.SpecFlow.dll.
  • Finally, the solution Explorer should look like this:

Consider a sample user story:

As an end user,
I would like to visit the google search page 
And then I would like to search an item so that
I can view the search results

Let me write a test scenario for the above story:

Given I am on the Google home page
When I search for text selenium
Then I should see the search results

Creating a new SpecFlow feature file:
  • Context-click on the project name ‘SpecflowTest‘ in the Solution Explorer
  • Select Add -> New Item
  • Select the ‘SpecFlow Feature File‘ and save it as ‘GoogleSearch.feature
 
 
 
 
 
  •  Specflow creates a new file “GoogleSearch.feature” and a designer file “GoogleSearch.feature.cs“. The default content of the Specflow file is in the Gherkin format.
  • The default content of the file is as shown is below:
Feature: Addition
 In order to avoid silly mistakes
 As a math idiot
 I want to be told the sum of two numbers

@mytag
Scenario: Add two numbers
 Given I have entered 50 into the calculator
 And I have entered 70 into the calculator
 When I press add
 Then the result should be 120 on the screen
  • Change the contents of the file to the new scenario as below and the Specflow generates a feature file ‘GoogleSearch.feature.cs’:
Feature: Google Search
 As an end user,
 I would like to visit the google search page
 And then I would like to search an item so that
 I can view the search results

@mytag
Scenario: Google Search
 Given I am on the Google home page
 When I search for text selenium
 Then I should see the search results

Creating a new SpecFlow Step Definition file:
  • Rename the class ‘Class1.cs‘ to ‘GoogleSearchStepDefinition.cs‘.
  • Context-click on the feature file ‘GoogleSearch.feature‘ and select …… System generates a specification file ‘…..’ as shown below.
  • Debug the project. Go to Projects -> Project Properties (‘SpecflowTest Properties‘ in my example).
  • Click on the ‘Debug‘ tab and set the ‘Start external program‘ to the location of NUnit exe file (C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0\nunit-x86.exe).
  • Build the solution, Go to ‘Build -> Build Solution‘ (hit the F6 key) in Visual Studio.
  • Execute the test, Go to ‘Debug -> Start Debugging‘ (hit the F5 key) in Visual Studio. Visual Studio invokes the NUnit application.
  • In NUnit, click on ‘File -> Open Project‘ and choose the location of the SpecflowTest.dll file.
  • In NUnit, click on the ‘Run‘ button to run the tests. Test shows Inconclusive result and the result is displayed in NUnit ‘Text Output’ tab.
  • Copy the contents of the NUnit  ‘Text Output‘ tab and paste it in the ‘GoogleSearchStepDefinition.cs‘ step definition file as shown below. The key point here is that the class needs to be annotated with the binding attribute and we can use the (.*) expression to represent variables coming from the feature file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
namespace SpecflowTest
{
 [Binding]
 class GoogleSearchStepDefinition
  {

  [Given(@"I am on the Google home page")]
  public void GivenIAmOnTheGoogleHomePage()
  {
  ScenarioContext.Current.Pending();
  }

  [When(@"I search for text (.*)")]
  public void WhenISearchForATextSelenium()
  {
  ScenarioContext.Current.Pending();
  }

  [Then(@"I should see the search results")]
  public void ThenIShouldSeeTheSearchResultsForSelenium()
  {
  ScenarioContext.Current.Pending();
  }
}
}
 
Creating a Static Browser class for defining the browser selection:
  • This class is a static helper class for selecting the browser and Selenium has support for Internet Explorer, Firefox and Chrome.
  • Context-click on the project name ‘SpecflowTest‘ in the Solution Explorer and select Add -> New Item
  • Create a C# file with name ‘WebBrowser.cs‘.
  • Now, copy and paste the code below to the ‘WebBrowser.cs‘.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
namespace SpecflowTest
{
   [Binding]
   public class WebBrowser
   {
     public static IWebDriver Current
     {
       get
       {
          if (!ScenarioContext.Current.ContainsKey("browser"))
          {
          //Select IE browser
          ScenarioContext.Current["browser"] = new InternetExplorerDriver();

          //Select Firefox browser
          //ScenarioContext.Current["browser"] = new FirefoxDriver();

          //Select Chrome browser
          //ScenarioContext.Current["browser"] = new ChromeDriver();
          }
        return (IWebDriver)ScenarioContext.Current["browser"];
        }
      }

    [AfterScenario]
    public static void Close()
    {
     if (ScenarioContext.Current.ContainsKey("browser"))
      {
          Current.Dispose();
      }
    }
  }
}

Implementing the Steps:
  • Remove all the methods ‘ScenarioContext.Current.Pending()
  • Now, copy and paste the code below to the ‘GoogleSearchStepDefinition.cs‘ as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SpecflowTest
{
 [Binding]
 public class StepDefinition1
 {

 [Given(@"I am on the Google home page")]
 public void GivenIAmOnTheGoogleHomePage()
 {
 //Navigate to the site
 WebBrowser.Current.Navigate().GoToUrl("http://www.google.com");
 //Check that the Title is what we are expecting
 Assert.AreEqual("Google", WebBrowser.Current.Title);
 }

 [When(@"I search for text (.*)")]
 public void WhenISearchForATextSelenium(string keyword)
 {
 // Find the text input element by its name
 IWebElement query = WebBrowser.Current.FindElement(By.Name("q"));
 // Input the search text
 query.SendKeys(keyword);
 // Now submit the form
 query.Submit();

  // Google's search is rendered dynamically with JavaScript.
  // Wait for the page to load, timeout after 5 seconds
  WebDriverWait wait = new WebDriverWait(WebBrowser.Current, TimeSpan.FromSeconds(5));
  IWebElement title = wait.Until<IWebElement>((d) =>
  {
  return d.FindElement(By.ClassName("ab_button"));
  });
 }

 [Then(@"I should see the search results")]
 public void ThenIShouldSeeTheSearchResultsForSelenium()
 {
 //Check that the Title is what we are expecting
 Assert.AreEqual("selenium - Google Search", WebBrowser.Current.Title);
 }

}
}
 
Executing the Tests:
  • Build the solution, Go to ‘Build -> Build Solution‘ (hit the F6 key) in Visual Studio.
  • Execute the test, Go to ‘Debug -> Start Debugging‘ (hit the F5 key) in Visual Studio. Visual Studio invokes the NUnit application.
  • In NUnit, click on ‘File -> Open Project‘ and choose the location of the SpecflowTest.dll file.
  • In NUnit, click on the ‘Run‘ button to run the tests. Test is executed using NUnit and the result will be displayed in NUnit GUI window as shown in the snapshot below.
About these ads
  1. April 20, 2012 at 8:50 am | #1

    Nice one!

    Very good details on each step. I like it!

    Just a short comment – both NUnit and SpecFlow can be installed via NuGet as well.
    Install-Package NUnit
    Install-Package SpecFlow

    Or in fact there’s someone created a package with those 2 bundled together:
    Install-Package SpecFlow.NUnit

    You still need to install the SpecFlow Visual Studio Integration to get that of course.

  2. April 23, 2012 at 2:51 am | #2

    Thanks Marcus!

  3. Scott
    May 29, 2012 at 10:02 am | #3

    Fantastic article, couldnt be more detailed if you tried, just what i have been looking for. I dont suppose you have executed and reported on these tests using a CI (jenkins for instance)

    • May 29, 2012 at 11:50 am | #4

      Thanks Scott, I will integrate this BDD test with CI tool such as Hudson/Jenkins using NAnt/MSBuild and will press it ASAP.

  4. Anu
    July 5, 2012 at 4:21 pm | #5

    What an excellent explanation Anoop. I am just about to learn SpecFlow with Selenium and found this blog. I want to thank you for all the effort you have put in on all your articles. Thanks alot. I think you are the one to approach for any doubts in future regarding Specflow and Selenium using C#.

  5. pratiksha mahamuni
    December 11, 2012 at 10:48 am | #7

    Can we use MVc3 razar in bdd having JSON Results

  6. QA Tester
    February 8, 2013 at 8:51 am | #9

    Unable to find SpecFlow Feature File to add to the project. Any mistake I am making while doing all the procedure?

  7. February 8, 2013 at 9:52 am | #10

    You need to install SpecFlow into Visual Studio (http://visualstudiogallery.msdn.microsoft.com/9915524d-7fb0-43c3-bb3c-a8a14fbd40ee) before the SpecFlow Feature files appears in the Add File-dialog

  8. QA Tester
    February 8, 2013 at 11:29 am | #11

    I’ve downloaded file from there and run it. Added a dll to References. Still unable to find SpecFlow Feature File. Whats wrong now :(

  9. February 12, 2013 at 11:14 am | #12

    Oh my goodness! Amazing article dude! Thank you, However I am encountering troubles with
    your RSS. I don’t know the reason why I cannot subscribe to it. Is there anybody else getting identical RSS issues? Anyone who knows the answer can you kindly respond? Thanks!!

  10. May 2, 2013 at 12:20 pm | #13

    I just started learning Selenium and found your blog very useful anoop. Thanks for the detailed post.. Expecting much more articles to learn…

  11. May 26, 2013 at 10:37 am | #14

    It’s going to be ending of mine day, but before end I am reading this impressive post to improve my know-how.

  12. June 14, 2013 at 9:10 am | #15

    Hi Anoop, Excellent postings.. They have been very helpful for my team. At the moment I am looking at ways we can run our tests headless for a Windows8 App. Our tests pass when we launch them via a browser, but fail when we try using headless HTMLUnit or PhantomJS.
    Has anyone experienced this before – Please kindly respond. Thanks!!

  13. June 20, 2013 at 5:57 am | #16

    You are so awesome! I do not suppose I have read a single thing like
    this before. So nice to find someone with a few original thoughts
    on this subject matter. Really.. thanks for starting this
    up. This site is one thing that’s needed on the internet, someone with some originality!

  14. ronin
    March 7, 2014 at 9:41 pm | #17

    Great step-by-step instructions! Thank you for sharing :)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: