Skip to main content

Data Driven Framework in Selenium


Data Driven Framework in Selenium




What is DataDriven?

In Data Driven Framework , We kept Test case logic resides in Test Scripts, the Test Data is separated and kept outside the Test Scripts.Test Data is read from the external files (Excel Files, CSV Files, Database) and are loaded into the variables inside the Test Script. Variables are used both for Input values and for Verification values. In Data Driven Framework Single Test case iterate over the Test Data. 

For example, We have Login test Case and we want to test it with Combination of Username and Password then in this case we will keep our Test Data in some external file and read this data and then pass it to our Test Script. Let's see how can we implement it.

As we know We are extending our existing framework further. First Let's see the Project Structure again.







We have already discussed this structure in our last tutorials. But we have some new files here. 
In TestData.xlsx file we will keep our Test Data, which later we will pass to our Parameterized Test Cases. Now let's understand the structure of TestData.xlsx file and see how can we read the data from this file.
(We are using Excel so to run this code in your local machine, First you need to configure the Apache POI in your project) 

In our TestData.xlsx file we have our test Data. Let's What it is - 

  1. We have seprate DataSheet for each TestClass. Like - LoginSheet for loginPageTest.Java Test Class, ProfileSheet for ProfilePageTest.java Test Class.  
  2. In each sheet we define the Test Data, specific to that sheet only. In the First Column we define the TestName, which should be similar to Test Name in the Test Script for which that TestSheet belongs. Like "loginTest" is our Test defined in theLoginPageTest.java Test file.
    After define the Test Name we will define the Test Data specific to that Test only. Each Column Define the Fields (to which we want to pass the Test Data) and Each Row define the Actual Test Data.

Here each sheet can contain the Data for multiple Tests. Like, suppose LoginTestPage.java have 5 Testcases. Similar to above sample sheet we will define the Test Data for all 5 tests in the single 'loginSheet' . We just need to take care testHeading in the testdata sheet should be similar to Test Name mentioned in the LoginPageTest. java file. 

Now We will see how can we read the Test Data from TestData file which is specific to TestCase only. 
For this we are creating an funtion in TestUtil.java file named getData() . As we have seen in the TestNG Tutorials , TestNG Data Provider reads the two dimentional array. SogetData() function returns us two dimentional array. 

We are implementing our code in such a way that our Two dimentional array will contain only one column and multiple rows
  • Each Row will contain the one Hashtable. (You can learn about HashTable form Here!)
  • Each hashtable will contain the Test Data for the TestCase in the form of key-value pair. Suppose we have 3 rows for our Test loginTest then getData() function array will contain the three hashtable, which we will pass to our Test Case. So our Test will iterate 3 times over Test Data. 

Now we will see, How can we read the Data from Test Data sheet.
  • First we will find the Row, from which the Test Starts.
  • Next, find number of columns for this Test Case. (This represents the Number of fields for Test)
  • Next, find Number of Rows for that test. (This represents the number of Data Rows)
  • Now put this Test Data into HashTable and put the HashTable into Two Dimentional Array.

Let's see how we can do it. Please note the below mentioned code. 








public static Object[][] getData(String sheetName, String testName) {
        
        //Read the TestData file location
        Xls_Reader xlsData = new Xls_Reader(Constants.TEST_DATA_FILE);
        int testStartRow = 0;
      
        // To find the Row Number from where our Test is being start
        for (int rNum = 1; rNum <= xlsData.getRowCount(sheetName); rNum++) {
            if (xlsData.getCellData(sheetName, 0, rNum).equalsIgnoreCase(testName)) {
                testStartRow = rNum;
                break;
            }
        }
        APPLICATION_LOGS.debug("Test Case " + testName+ " starts from Row Number " + testStartRow);

        // This will denote from which column starts for the test
        int colStartTest = testStartRow + 1;

        // Denote the Total Columns in the Test
        int totalCol = 0;
        //To find number of Columns in the Test
        while (!xlsData.getCellData(sheetName, totalCol, colStartTest).equals("")) {
            totalCol++;
        }
     
        APPLICATION_LOGS.debug("Test Case " + testName + " has total columns "
                + totalCol);

        //Denote number of Rows Present for Test Data
        int rowStartTestData=testStartRow+2;
        int totalRows = 0;

        //To find the Number of Rows for Test Data Present 
        while (!xlsData.getCellData(sheetName, 0, rowStartTestData+totalRows).equals("")) {
            totalRows++;
        }
 
        APPLICATION_LOGS.debug("Test Case " + testName + " Test Data has Total Rows "
                + totalRows);
        System.out.println(" ");
     
        //Extract Data and Store it in Data Array
        Object[][] data = new Object[totalRows][1];
        Hashtable<String, String> datatable = null;
        int dataIndex =0;
     
        for(int rNum=rowStartTestData; rNum<(rowStartTestData+totalRows); rNum++){
            datatable = new Hashtable<String, String>();
         
            for(int cNum=0; cNum<=totalCol; cNum++){
                 datatable.put(xlsData.getCellData(sheetName, cNum, colStartTest), xlsData.getCellData(sheetName, cNum, rNum));
                System.out.print(xlsData.getCellData(sheetName, cNum, rNum) +" ");
            }
         
            /* It will put the Data into the Table for Each row and then
             * put the table inside the Two dimensional Array
            */

            data[dataIndex][0]=datatable;
            dataIndex++;
        }
        APPLICATION_LOGS.debug("Data Extracted from the Excel file successfully");
        return data;
    }
























































































































































The above function will return the two dimentional array and that array will contain the Test Data & TestCase Name.

Now we will see how can we use this with our TestCase. To use this function, We will implement the DataProvider in our Test Class and which should be specific to Test Case and then use that Data Provider. Let's see understand this with the help of below mentioned code.
package com.seleniumbix.TestCases;

public class LoginPageTest extends TestBase {
  
    @DataProvider
    public Object[][] getLoginData(){
        return TestUtil.getData("LoginSheet", "loginTest");
    }
    @Test(dataProvider="getLoginData")
    public void loginTest(Hashtable<String, String> data) {
        TestUtil.checkRunMode("LoginSheet", "loginTest");
        LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
        HomePage homePage = loginPage.doLogin(data.get("UserName"),data.get("Password"));
        homePage.verifyPage(data.get("PageTitle"));
    }
}






In the above code we have declared the DataProvider. In the DataProvider we are reading the Data for LoginTest. We are just passing the SheetName and TestName to getData() function and this will return the HashTable
This HashTable will return the values in Key-value pair. Here Key always will be same and values will vary according to the data mentioned in the Data Sheet.
(As per the getData() code for loginTest key will be Username and Password, and Values will be depend on number of rows mentioned for the TestCase.)

You can see in the above @Test annotation we have declared our TestCase code. We have implemented the Test case loginTest , Which is using the DataProvider namedgetLoginData. In this TestMenthod we have passed an HashTable to get the data from dataProvider.
  • First we are checking the Runmode of the TestCase.
  • Then we are opening the LoginPage.
  • In next step we are trying to login into application using doLogin() function. In doLogin() function we are getting the data form HashTable using get() function, this HashTable is getting the Data form getData() function. The key is username and Password. 
  • This Test will iterate over the data i.e If we have 3 rows in our Test Data for username and password then this Test case will run three times. 

We are uploading the complete Framework code here in .doc file. You can down it and run it in your local machine. We have already uploaded the Project structure above. Download the code arrange it as per define project structure and execute. 

You can Downnload the TestData file form Here.(Download TestCases.xlsx) (Download TestData.xlsx)

Download the Complete Project code form here.(Download Project Code)













Comments

Popular posts from this blog

Autonium

About Autonium Autonium is a test automation framework for web applications. This framework is built by using Java and Selenium. It uses Maven project structure. Easy to understand and use it. Having basic idea on Java, Selenium, Maven and TestNG is good enough to start with Autonium. Let’s start Automation with Autonium --------------------------------------------------- Advantages Provides support to all major browsers –  Firefox, Chrome, IE and Safari . Capability of executing scripts on  Remote Machines  by using Selenium Server. Users can make use of Selenium Web driver methods and Autonium methods. Autonium simplifies  Test data management . Test data can be read from properties files. Scripts can be developed without  hard coding  test data . Identifiers can also be read from properties files and  hard coding   of identifiers can be avoided. Test data and Identifier v...

ExtentReports in Selenium Webdriver

ExtentReports in Selenium Webdriver What is ExtentReport? ExtentReports  is a HTML reporting library for Selenium WebDriver for Java which is extremely easy to use and creates beautiful execution reports. It shows test and step summary, test steps and status in a toggle view for quick analysis Download Download the jar below: Download ExtentReports 1.4 (1623)    Snapshot of Extent report After Executing the Script   Program Steps:  We are going to write three different testcases. Pass Warning Fail TestCase with Pass Result Navigate to http://www.guvi.in Click on Sign-in Enter the credientials Check the URL is correct or not after login   TestCase with Warning Result Verify with the Wrong URL (static String Afterloginfail="http://www.guvi.in/ ")    TestCase with fail Result Click on Menu Select Tech Challenges Verify With wrong URL. Source Code: import  java.io.File; import  j...

API Testing With Selenium WebDriver

REST API Testing Framework We will be creating a simple Rest Testing Framework in Java and JUnit that could be used for any testing scenarios. Rest Testing Framework Overview The framework should be able to execute the basic REST operations (GET, POST, PUT, PATCH, DELETE) and perform the validations on the code, message, headers and body of the response. The completed code can be accessed from my  GitHub account   from where you can collect and make modifications based on your requirements. Design We will be having three classes for the framework (in package com.axatrikx.controller ) RestExecutor  : Performs the HTTP operations using Apache Http Client RestResponse  : A javabean class to hold our response values (code, message, headers, body) RestValidator  : Validates the response with the expected values The package  com.axatrikx.test  holds the test scripts. Note: I will be using ‘ json-server ‘ to f...