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...

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       ...

Page Object Model && Page Factory

Page Object Model Design Pattern (POM): Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication. In Selenium all we are doing is finding elements and filling values for those elements. For small script it’s easy to maintain . But with time test suite will grow. As we add more and more lines to our code, things become tough.The chief problem with script maintenance is that if 10 different scripts are using the same page element, with any change in that element, we need to change all 10 scripts. This is time consuming and error prone. A better approach to script maintenance is to create a separate class file which would find web elements, fill them or verify them. This class can be reused in all the scripts using that element. In future, if there is a change in the web element, we need to make the change in just 1 class file and not 1...