Earlier we learnt how to perform data driven testing using Java Excel API to read data from excel file In THIS POST. We have also used Apache POI API to read data from excel file In data driven framework creation. Steps to create data driven framework are given on THIS PAGE. Now let's
read data from CSV file to perform data driven testing In selenium WebDriver. Bellow given steps will show you how to read data from from CSV file.Download required files
We need opencsv-3.2.jar file to read data from CSV file and I have prepared sample CSV data file (Detail.csv) to use It In bellow given example.
- DOWNLOAD and extract zip folder to get both above files.
- Add "opencsv-3.2.jar" file In your project's build path In eclipse. You can learn how to add external jar files In project's build path In THIS POST.
- Copy paste "Detail.csv" file In D: drive.
"Detail.csv" file have some data and we will use that data In out test. Main thing to learn here Is how to read that data from CSV file.
Now run bellow given example In Eclipse. It will read data from CSV file and use It In webdriver test case to fill form fields.
package Testing_Pack;
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 CSVRead {
//Provide CSV file path. It Is In D: Drive.
String CSV_PATH="D:\\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("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@Test
public void csvDataRead() throws IOException{
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 FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys(FName);
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys(LName);
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys(Email);
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys(Mob);
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys(company);
driver.findElement(By.xpath("//input[@value='Submit']")).click();
driver.switchTo().alert().accept();
}
}
}
No comments:
Post a Comment