Road to data driven testing webdriver C# with Nunit

In this post I will show you how to implement data driven testing in webdriver C# using Nunit.
I put all data in xml file and fetch data during execution time of test. For data I have created data.xml file list country.


Below DataDriven.cs file in which I have created a webdriver test for Wikipedia where I fetch data from xml file, search and verify country in Wikipedia.

using System.Xml.Linq;
using NUnit.Framework;
using System.Collections;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Collections.Generic;
using System.Linq;
using System;

namespace WebdriverTests
{
    [TestFixture]
    public class DataDriven
    {
        private IWebDriver driver;
        private string baseURL;    
       
        [SetUp]
        public void SetupTest()
        {
            driver = new FirefoxDriver();
            baseURL = "http://en.wikipedia.org/";          
        }
       
        [TearDown]
        public void TeardownTest()
        {
           driver.Quit();          
        }

         [TestCaseSource("TestData")]
        public void DataDriven1Test( string country, string desc)
        {
            driver.Navigate().GoToUrl(baseURL + "wiki/Main_Page");
            driver.FindElement(By.Id("searchInput")).Clear();
            driver.FindElement(By.Id("searchInput")).SendKeys(country);
            driver.FindElement(By.Id("searchButton")).Click();
            String dd = driver.FindElement(By.XPath("//tr[@class='adr']/th/span")).Text;
            Console.WriteLine(dd);
            Assert.True(country.Equals(dd.Trim()));
        }

        private IEnumerable TestData()
        {
            // read data from xml file
            var doc = XDocument.Load(@"c:\Data.xml");         
            return
                from vars in doc.Descendants("vars")
                    let country = vars.Attribute("country").Value
                    let desc = vars.Attribute("desc").Value            
                select new object[] { country, desc };
        }
      
    }
}
TestData() function read all associated data from xml file and  using [TestCaseSource("TestData")] data pass into webdriver test.

3 comments:

  1. Good post for data driven testing in C# webdriver. How we can do same with excel sheet

    ReplyDelete
  2. Same question...how will we do the same with an excel sheet that contains a series of test cases written?????

    ReplyDelete
  3. please find here more flexible solution of passing test data from xml files to tests as dictionary
    https://github.com/ObjectivityBSS/Test.Automation/wiki/DataDriven-tests-from-Xml-files

    ReplyDelete

Leave your comments, queries, suggestion I will try to provide solution