Monday, September 8, 2014

TestNG - Data Provider Magic

In my experience, I have used data provider to the core. It's just awesome if you want to iterate through a single flow with multiple data. Your data source could be from any form, like excel, csv.. Just follow the steps to pass data to any test method.

@DataProvider(name = "dataSupplier", parallel = false)
public Object[][] data() throws Exception {
Object[][] retObjArr={{"7165"},{"7166"},{"7167"},{"7168"},{"7169"},{"7170"},{"7171"},{"7172"},{"7173"},{"7174"},{"7175"},{"7176"},{"7177"},{"7178"}};
return(retObjArr);
}


@Test(dataProvider = "dataSupplier")       // Here I am telling the test case to use the dataprovider "dataSupplier"
public void test1(String s) throws InterruptedException {
System.out.println(s);
}

You are done..!!!  It now prints all the numbers if you run the test case once and you could see an excellent report which says 14 tests passed :)


Same way you could do this with excel by using apache poi or jxl api like the below example.

@DataProvider(name = "data-provider", parallel = false)
public Object[][] data() throws Exception {
Object[][] retObjArr=getTableArray("C:\\QA\\ws\\nu\\src\\test\\resources\\test.xls");
return(retObjArr);
}


public String[][] getTableArray(String xlFilePath) throws Exception{
String[][] tabArray=null;
Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
Sheet wrksheet = workbook.getSheet(0);

String tabdata[][] = new String[wrksheet.getRows()][wrksheet.getColumns()];
for (int i = 1; i < wrksheet.getRows(); i++) {
for (int j = 0; j < wrksheet.getColumns(); j++) {
tabdata[i][j] = wrksheet.getCell(j, i).getContents();
}
}
return(tabdata);
}
Here you are returning the data as objects.. Look at the below test which uses this data-provider and how it receives the data. It supplies 2 strings - link and response code from the data provider.

@Test(dataProvider="data-provider")
public final void test2(String link, String responsecode) throws InterruptedException {
if(link != null){
Assert.assertNotEquals(responsecode,"404");}
}






No comments:

Post a Comment