In this post will implement how to read the data from CSV file.
Prerequisite :
Download the OpenCSV jar from : https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |