Wednesday, February 8, 2017

TestNG - DataDriven Test with CSV

In this post will implement how to read the data from CSV file.

Prerequisite : 
Test data file : Details.csv
testprojestname,test desc
testprojestname11,test desc3

testprojestname21,test desc2


Scenario : Open AnukoTimeSheet and add project by reading Details.csv test data file 


package com.testng;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.opencsv.CSVReader;
public class ReadDAtaFromCSV {
//Provide CSV file path. It Is In D: Drive.
String CSV_PATH="yourpath/Detail.csv";
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://timetracker.anuko.com/login.php");
driver.findElement(By.id("login")).sendKeys("guest");
driver.findElement(By.id("password")).sendKeys("guest");
driver.findElement(By.id("btn_login")).click();
}
@Test
public void csvDataRead() throws IOException, InterruptedException{
driver.findElement(By.linkText("Projects")).click();
driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/table[5]/tbody/tr/td/table[2]/tbody/tr/td/form/input")).click();
Thread.sleep(5000);
CSVReader reader = new CSVReader(new FileReader(CSV_PATH));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String pname = csvCell[0];
String pdesc = csvCell[1];
driver.findElement(By.xpath("//*[@id='project_name']")).sendKeys(pname);
driver.findElement(By.xpath("//*[@id='description']")).sendKeys(pdesc);
driver.findElement(By.id("btn_add")).click();
// to click on project
driver.findElement(By.linkText("Projects")).click();
driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/table[5]/tbody/tr/td/table[2]/tbody/tr/td/form/input")).click();
Thread.sleep(5000);
}
}
}