Skip to main content

Data Driven Testing using Selenium in C#


Data Driven Testing

Data-driven is a test automation framework which  focused on separating the test scripts logic and the test data from each other. It allows us to have a single test script which can execute tests for all the test data in the table. The test data set is kept in the external files or resources such as Excel Sheets, SQL Database, XML files etc.The test scripts connect to the external resources to get the test data. By using this framework we could easily make the test scripts work properly for different sets of test data. This framework significantly reduces the number of test scripts compared to a modular based framework.

Advantages of using Data Driven Test Framework
We adopt Data Driven Framework when we have to execute the same script with multiple sets of test data.If we run the same test with multiple test data sets manually it's time-consuming and error-prone.
Advantages->
Re-usability of code
Improves test coverage
Faster Execution
Less maintenance
Permits better error handling

Data driven framework in selenium webdriver using Excel files 
Here in my sample code selenium webdriver opens the browser and search for “Selenium”.We read the url and the search word from the excel file.

1. Create Excel file “TestData.xlsx” in the desired folder of the PC.
        Fill the data in the excel file like below.


 2. Install ExcelDataReader 
      Reference->Manage Nuget Packages->Browse->ExcelDataReader   
      
3. To open the Excel sheet and read data from it within  Selenium test script, I use following piece of code.
     #region Excel 
    public class ExcelLib
    {
        static List<Datacollection> dataCol = new List<Datacollection>();
        public class Datacollection
        {
            public int rowNumber { get; set; }
            public string colName { get; set; }
            public string colValue { get; set; }
        }
        public static void ClearData()
        {
            dataCol.Clear();
        }
        private static DataTable ExcelToDataTable(string fileName, string SheetName)
        {
            // Open file and return as Stream
            using (System.IO.FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream))
                {
                    excelReader.IsFirstRowAsColumnNames = true;
                    //Return as dataset
                    DataSet result = excelReader.AsDataSet();
                    //Get all the tables
                    DataTableCollection table = result.Tables;
                    // store it in data table
                    DataTable resultTable = table[SheetName];
                    //excelReader.Dispose();
                    //excelReader.Close();
                    // return
                    return resultTable;
                }
            }
        }
        public static string ReadData(int rowNumber, string columnName)
        {
            try
            {
                //Retriving Data using LINQ to reduce much of iterations
                rowNumber = rowNumber - 1;
                string data = (from colData in dataCol
                               where colData.colName == columnName && colData.rowNumber == rowNumber
                               select colData.colValue).SingleOrDefault();
                //var datas = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
                return data.ToString();
            }

            catch (Exception e)
            {
                //Added by Kumar
                Console.WriteLine("Exception occurred in ExcelLib Class ReadData Method!" + Environment.NewLine + e.Message.ToString());
                return null;
            }
        }
        public static void PopulateInCollection(string fileName, string SheetName)
        {
            ExcelLib.ClearData();
            DataTable table = ExcelToDataTable(fileName, SheetName);
            //Iterate through the rows and columns of the Table
            for (int row = 1; row <= table.Rows.Count; row++)
            {
                for (int col = 0; col < table.Columns.Count; col++)
                {
                    Datacollection dtTable = new Datacollection()
                    {
                        rowNumber = row,
                        colName = table.Columns[col].ColumnName,
                        colValue = table.Rows[row - 1][col].ToString()
                    };
                    //Add all the details for each row
                    dataCol.Add(dtTable);
                }
            }

        }
    }
    #endregion
      4. Show the path of the excel file  and send “Row number” and “Column Name” in parameter.
  class Program
    {
       public static String ExcelPath = @"";
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            ExcelLib.PopulateInCollection(ExcelPath, "Data");
            driver.Navigate().GoToUrl(ExcelLib.ReadData(2, "Value"));//Fetching data from Excel
            var searchbox = driver.FindElement(By.Id("lst-ib"));
            searchbox.SendKeys(ExcelLib.ReadData(3, "Value"));//Fetching data from Excel

            searchbox.SendKeys(Keys.Enter);
            driver.Close();
        }

5. Output of the code



Comments

Popular posts from this blog

JIRA OverView

What is JIRA? JIRA is a project management tool used for issues and bugs tracking system for all types of testing.The JIRA dashboard consists of many useful functions and features which make handling of issues easy. The following points explain some interesting details of JIRA. • JIRA is an incident management tool. • JIRA is not an acronym, the name 'JIRA' comes from the Japanese word 'Gojira' • JIRA is developed by Australian Company Atlassian • JIRA is a platform independent tool; it can be used with any OS. • JIRA is multi-lingual tool − English, French, German, Japanese, Spanish, etc. • JIRA can be integrated with many other tools like GitHub, Team Foundation Software and many more. • JIRA is a commercial tool and available as a Trial version for a limited time. • To utilize JIRA services, a license is required. Features: JIRA is one the best product management tool which includes: Issue tracking & management: A software application that allows to...

Generating Extent Reports in C#

In software test automation after completion of the test suite execution we need to have a report for the execution status and it is one way of evidence for the pass and fail status of the tests. Extent reports are very rich HTML reports for the selenium webdriver.. By using these reports we can provide lots of information to the reports. Some advantages of Extent Reports: 1.Status will be shown in the form of PIE chart. 2.Can give the our own name to the test method (i.e can change the test method name in the report). 3.Can generate stepwise log information in the report. 4.Can segregate the tests using Test Categories. 5.Can give test author name to display in the report. 6.Can show the screenshots in the report wherever we need. 7.Can add our own information in the report (i.e. version of selenium used, Environment information where the test suite executed). 8.It will give the System information in the report (i.e. HostName and OS used to execute the t...

Demo Project (Specflow Setup)

Installation and Setup Steps-->     1.Install SpecFlow for Visual Studio (Open Extensions and Updates) 2. Install SpecFlow NuGet Packages     3. Add Feature File    My Demo Project    Here, I have worked on following story    Story: Discounts on online shopping cart price for loyalty card customers    In order to increase the reward for loyal customers    I want to add 5-10% discounts on the final shopping cart price.    Scenario 1: 5% discount for loyalty card customer    Given a loyalty card customer in online checkout page    When the shopping card total is less than $100    Then 5% discount should be applied to the final shopping cart price.     Create Scenarios    In the feature file, I described what the feature needs to do Every scenario represents a different       ...