Data Driven Testing Using Selenium (webdriver) in C#

 In this article, I would like to explain about performing data driven testing in Selenium. 

I have used C# language and for IDE is Visual Studio 2010 Ultimate edition to achieve our aim. As we will proceed we will know, step by step how to Create a Data Driven Test method using Selenium in .Net. So for now, let's roll our sleeve and get going.

Before going into details, it would be better to provide a synopsis of a few things so that even you can become familiar with everything. And as I will proceed you will not feel cut off from the main theme. 

Selenium

Selenium is a portable software testing framework for web applications. Selenium provides a record/playback tool for authoring tests without learning a test scripting language (Selenium IDE). It also provides a test domain-specific language (Selenese) to write tests in a number of popular programming languages, including C#, Java, Groovy, Perl, PHP, Python and Ruby. The tests can then be run against most modern web browsers. Selenium deploys on Windows, Linux, and Macintosh platforms.

(Source: http://en.wikipedia.org/wiki/Selenium_(software))

I will refrain from going into details about Selenium. Since there is tons of documentation and information available on the internet which already explain Selenium. You can go through over there.

You can visit the Selenium official website for the documentation:

http://seleniumhq.org/ 

Download the Selenium for .Net from here:

http://seleniumhq.org/download/

Apart from that you can visit my blog also to get to know the Selenium web driver using .Net.

http://seleniumdotnet.blogspot.com/.

Data Driven Testing

Data driven testing is an action through which a set of test input and/or output values are read from data files (ODBC source, CSV files, Excel files, DAO objects, ADO objects etc) and are loaded into variables in captured or manually coded script. Data-Driven testing generally means executing a set of steps with multiple sets of data. Selenium does not provide any out-of-the box solution for data driven testing but leaves it up to the user to implement this on his own. That is why we are here; to do out of box.

Code:

Prerequisites

  • Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.

So now our main coding will start from here:

We will be using the Unit testing feature provided by VS2010 and C# code for the same.

  1. Select Unit test as project from VS2010

    1.1 Open your VS2010
    1.2 Click on the Test Tab and select New test

    DDT1.gif

    1.3 Click on Unit test from the New open window 

    DDT2.gif

    Figure1. Select Unit Test from VS2010

    1.4 Rename the File to SeleniumTest.cs
     
  2. Add Selenium web driver references

    2.1 Add the following dlls through add references:

    DDT3.gif

    Figure2. Add Selenium DLL in the project.
     
  3. Open the selenium.cs file and add the following Name space:

     
    using OpenQA.Selenium;
    using
    OpenQA.Selenium.IE;
    //add this name space to access WebDriverWait
    using OpenQA.Selenium.Support.UI;
    Never try to add this forcefully unless you are not getting it with your VS intelligence.
Test Initialization:

  public static IWebDriver WebDriver;
  // Use TestInitialize to run code before running each test 
  [TestInitialize()]
  public void MyTestInitialize()
  {
    var capabilitiesInternet = new OpenQA.Selenium.Remote.DesiredCapabilities();
    capabilitiesInternet.SetCapability(
"ignoreProtectedModeSettings"true);
    WebDriver = 
new InternetExplorerDriver(capabilitiesInternet);
   }
Test CleanUp

  // Use TestCleanup to run code after each test has run
  [TestCleanup()]
  public void MyTestCleanup()
  {
     WebDriver.Quit();
  }

Before implementing the test method for data driven we will write the Selenium Test method without Data Driven. Then we will go for Data Driven Testing, by doing this scenario you will clearly understand the difference between a simple Selenium test method without data driven and Selenium test method with Data Driven.

Selenium Test Method without Data Driven

To write Automation code using Selenium to automate our target website we will use any web application. Here I will use a http://www.x-rates.com/calculator.html web application for our AUT (Application under Test) purpose. The function of this AUT web application is to compare a currency value from one country's currency to another country's currency.

NOTE: The AUT website is just for demo purposes. The currency rate would not be fixed. So perhaps the test cases pass for me but would fail for you or vise-versa.

The web page is as below:

DDT4.gif

Figure 3. Application Under test

Now we will write our Selenium Test method to perform the following operation:
  1. Select Value into the first dropdown box (convert)
  2. Select value into the second dropdown box (into)
  3. Click on the Calculate button to get the currency value w.r.t first country's currency selected.
  4. Read the value from upper textbox/input box. This will be our actual result.
  5. Compare the actual value from the expected value.

     
     [TestMethod]
            public void TestCurrencyConvertorWithoutDDT()
            {
               //Read your first country currency name
     
               var convertVal = "American Dollar";
                //Read your second contry currency
     
               var inToVal = "Indian Rupee";
                //Read Expected value from data source
     
               var expectedValue = "49.7597 INR";
                //Goto the Target website
     
               WebDriver.Navigate().GoToUrl("http://www.x-
    rates.com/calculator.html");
                var setValueConvert = WebDriver.FindElement(By.Name("from"));
                var setValueInto = WebDriver.FindElement(By.Name("to"));
                var calculateButton = WebDriver.FindElement(By.Name("Calculate"));
                var outPutvalue = WebDriver.FindElement(By.Name("outV"));
                var selectConvertItem = new SelectElement(setValueConvert);
                var selectIntoItem = new SelectElement(setValueInto);
                selectConvertItem.SelectByText(convertVal);
                selectIntoItem.SelectByText(inToVal);
                calculateButton.Click();
                var currencyValue = outPutvalue.GetAttribute("value");

                Thread.Sleep(900);//Not a good practise to use Sleep
                //Get the screen shot of the web page and save it on local disk 
                SaveScreenShot(WebDriver.Title);
                Assert.AreEqual(expectedValue, currencyValue.Trim());
           }


Run the above Test method to see the result:
  1. On the Test menu, click Windows and then select Test View.

    DDT5.gif

    Figure 4. Select Test View

    The Test View window is displayed.

    DDT6.gif

    Figure 5. Test View Window
     
  2. Right-click TestCurrencyConvertorWithoutDDT and click Run Selection. 

    If the Test Results window is not already open, it opens now. The TestCurrencyConvertorWithoutDDT test runs.

    In the Result column in the Test Results window, the test status is displayed as Running while the test is running. 
     
  3. In the Test Results window, right-click the row that represents the test and then click View Test Results Details.

    DDT7.gif

    Figure 6. Test Results Windows


Test Method as Data Driven

As you have already seen in the above Selenium test method we ran our method for only one set of values. Now in Data Driven we will run the same method with multiple sets of inputs value.

To read the input values against which we are going to run our Test method, we have stored our input values into a data Source. For that we will use a CSV file, but you can also use other data sources such as Excel Sheet etc. 
In this CSV file we will store our expected result also so that we can compare our actual output with this value.

Our csv will look something like this (give the name to this csv file as DDT.csv):

DDT8.gif

Figure 7. CSV file as Data Source

Now we will connect the above Test method to our data Source [here it is DDT.CSV]
  1. Open the solution that contains the test method for which you want to use a data source.
  2. On the Test menu, point to Windows, and then click Test View.
  3. In the Test View window, right-click the unit test for which you want to use a data source and then click Properties.

    DDT9.gif

    Figure 8. Properties of Selenium Test Method
     
  4. In the Properties window click Data Connection String and then click the ellipses(…).

    DDT10.gif

    Figure 9. Test Data Source Wizard
     
  5. Follow the instructions in the in the New Test Data Source Wizard to create the data connection.

    A connection string is added to your unit test after the first bracket of the [TestMethod()] element.

    It would be something like this:
     
     [DeploymentItem("AutomationUsingSeleniumTest\\DDT.csv"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\DDT.csv", "DDT#csv", DataAccessMethod.Sequential)]
     
  6. Now we will assign variables to values from your data source

    6.1 Open the Test file that contains the test method for which you want to use a data source and locate the variables in the test method.

    6.2 For each variable that you want to come from the data source, use the syntax TestContext.DataRow["NameOfColumn"].

    The piece of code would be as below:
     
    //Read your first country currency name
    var convertVal = TestContext.DataRow["FirstCountryByText"].ToString();
    //Read your second contry currency
    var inToVal = TestContext.DataRow["SecondCountryByText"].ToString();
    //Read Expected value from data source
    var expectedValue = TestContext.DataRow["ExpectedValue"].ToString();

    The whole Code of the Test Method would be as below:

     
     DeploymentItem("AutomationUsingSeleniumTest\\DDT.csv"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\DDT.csv", "DDT#csv", DataAccessMethod.Sequential)]
          [TestMethod]
         
    public void TestCurrencyConvertorWithDDT()
          {
              //Read your first country currency name
              var convertVal = TestContext.DataRow["FirstCountryByText"].ToString();
             //Read your second contry currency
              var inToVal = TestContext.DataRow["SecondCountryByText"].ToString();
              //Read Expected value from data source
              var expectedValue = TestContext.DataRow["ExpectedValue"].ToString();
              //Goto the Target website
              WebDriver.Navigate().GoToUrl("http://www.x-rates.com/calculator.html");
              var setValueConvert = WebDriver.FindElement(By.Name("from"));
              var setValueInto = WebDriver.FindElement(By.Name("to"));
              var calculateButton = WebDriver.FindElement(By.Name("Calculate"));
              var outPutvalue = WebDriver.FindElement(By.Name("outV"));

              var selectConvertItem=newSelectElement(setValueConvert);
              var selectIntoItem =newSelectElement(setValueInto);
             selectConvertItem.SelectByText(convertVal);
              selectIntoItem.SelectByText(inToVal);
              calculateButton.Click();
              var currencyValue =outPutvalue.GetAttribute("value");
              Thread.Sleep(900);//Not a good practise to use Sleep
              //Get the screen shot of the web page and save it on local disk
              SaveScreenShot(WebDriver.Title);
             Assert.AreEqual(expectedValue,currencyValue.Trim());
          }

     
  7. Run the Test Method (I already explained this) and the Result will be something like below:

    DDT11.gif

    Figure 10. Data Driven Test Results

    So you can clearly see that the Test method has ran for 4 different sets of values. And it fetched the input values from our specified data source; that is DDT.csv.

Download the code to get the whole piece of code. I have used a method that is SaveScreenShot(WebDriver.Title). You can get the code details along with the uploaded code. Actually this method would take the screen shot of your target web page and will store that in the Test Result directory. 

Save Screen Shot Method
/// <summary>
/// This will Take the screen shot of the webpage and will save it at particular location
/// </summary>      ///
<param name="screenshotFirstName"></param>
private static void SaveScreenShot(string screenshotFirstName)
{
    var folderLocation = Environment.CurrentDirectory.Replace("Out","\\ScreenShot\\");
    if (!Directory.Exists(folderLocation))
    {
        Directory.CreateDirectory(folderLocation);
    }
    var screenshot = ((ITakesScreenshot)WebDriver).GetScreenshot();
    var filename = new StringBuilder(folderLocation);
    filename.Append(screenshotFirstName);
    filename.Append(DateTime.Now.ToString("dd-mm-yyyy HH_mm_ss"));
    filename.Append(".png");
    screenshot.SaveAsFile(filename.ToString(), System.Drawing.Imaging.ImageFormat.Png);
}
 

The Screen shot of your Target web page will be saved as below:

DDT12.gif

Figure 11. Screen Shot saved at Test Result folder.

Feel free to provide your valuable feedback and comments!!

For any issue/question/suggestion in Selenium for C# you can refer to this blog: http://seleniumdotnet.blogspot.com/