Data Provider In Selenium

Data Provider: By using data provider we can test with multiple sets of Data for same scenarios.

Here in @Test method you can consider the number of columns are the number of arguments.
The arguments have been added in a respective order in object array while storing.
Once the @Test annotation found with 'dataProvider' keyword, it will call the @DataProvider method.
After that @DataProvider  method will start iterating and it will end while @Test method will finish the execution for all the rows of your excel sheet.
Here the @Test method will execute the number of times rows are there in the sheet.
Ex:
Open the browser and open facebook.com
Get the 1st row data from excel sheet and pass that as ur input like userName, password, and expectedTitle .After that click on login button.
Get the title of the page in run time after login and verify with expectedTitle.
close the browser
Then again fetch the data from 2nd row.Like this it will execute all rows data.



public class DataProviderExample
{
    @Test(dataProvider="Data")
    public void login(String userName, String password, String expectedTitle) throws InterruptedException{
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("www.facebook.com");
         driver.findElement(By.id("username")).sendKeys(userName);
        driver.findElement(By.id("passwd")).sendKeys(pass);
        driver.findElement(By.xpath("//button[contains(text(),'Sign in')]")).click();
     
        Thread.sleep(2000);
        String actualTitle = driver.getTitle();
        try{
            Assert.assertEquals(actualTitle , expectedTitle);
            driver.close();
        }catch(Exception e){
            driver.close();
        }
     
    }
    @DataProvider(name="Data")
    public static Iterator fetchData() throws InvalidFormatException, IOException{
        ArrayList newData = new ArrayList();
        FileInputStream fis = new FileInputStream("./TestData.xlsx");
        Workbook wb = WorkbookFactory.create(fis);
        Sheet sh = wb.getSheet("Sheet2");
        int numOfRows = sh.getLastRowNum();
        String userName, password, expectedTitle;
        for(int i=0; i<numOfRows; i++){
            userName = sh.getRow(i).getCell(0).getStringCellValue();
            password = sh.getRow(i).getCell(1).getStringCellValue();
            expectedTitle = sh.getRow(i).getCell(2).getStringCellValue();
            myData.add(new Object[]{userName,password,expectedTitle});
        }
        return newData .iterator();
    }
}


What is return data type of DataProvider?
Ans- TestNg dataprovider supports 2 types as return type 
1) 2 dimensional array of any type ex: Object[][] or String[][]
2) Iterator of single dimensional array of any type
 ex: Iterator<String[]>

Copyright © 2017 qatoolsguide.blogspot.com || ALL RIGHTS RESERVED