It is recommended that we store the test data separately from the test scripts.
This data can be exported in CSV format. We can read CSV files using Java IO and utility classes.
In this blog, we will read data from a CSV file and use this data to execute the test script.
Preconditions:
– Set up a new project and add JUnit4 to the project’s build path.
– Create the CSV file with the required data.
Here are our test data to the CSV file:
TesterFname1, TesterLName1, email1@email.com, password
TesterFname2, TesterLName2, email2@email.com, password
TesterFname3, TesterLName3, email3@email.com, password
TesterFname4, TesterLName4, email4@email.com, password
Here is a sample code how to create a parameterized test with CSV.
Do the following steps:
1. Create a new JUnit test class that uses a parameterized runner using
@RunWith(value = Parameterized.class).
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) public class dataDrivenJUnitTestWithCSV{ private static WebDriver driver; private String firstName; private String lastName; private String email; private String password; }
2. Add the testData() method, which will return test data from the CSV file as a collection. This method internally calls the getTestData() method. Also add a constructor to the dataDrivenJUnitTest class, which will be used by the test runner to pass the parameters to the dataDrivenJUnitTest class instance.
@Parameters public static Collection testData() throws IOException { return getTestData("C:\\data.csv"); } public dataDrivenJUnitTestWithCSV(String firstName, String lastName, String email, String password) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; }
3. Add the getTestData() method, which reads a CSV file and returns the data in the collection.
public static Collection<String[]> getTestData(String fileName) throws IOException { List<String[]> records = new ArrayList<String[]>(); String record; BufferedReader file = new BufferedReader(new FileReader(fileName)); while ((record = file.readLine()) != null) { String fields[] = record.split(","); records.add(fields); } file.close(); return records; }
4. Finally, add the test case method testFacebookRegistration() that uses parameterizedvariables. Also, add the setup() and teardown() methods to the dataDrivenJUnitTest class.
Here is the full code:
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @RunWith(value = Parameterized.class) public class dataDrivenJUnitTestWithCSV { private static WebDriver driver; @Before public void setUp() { driver = new FirefoxDriver(); driver.get("https://www.facebook.com/"); } @After public void tearDown() { driver.quit(); } private String firstName; private String lastName; private String email; private String password; @Parameters public static Collection testData() throws IOException { return getTestData("C:\\data.csv"); } public dataDrivenJUnitTestWithCSV(String firstName, String lastName, String email, String password) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public static Collection<String[]> getTestData(String fileName) throws IOException { List<String[]> records = new ArrayList<String[]>(); String record; BufferedReader file = new BufferedReader(new FileReader(fileName)); while ((record = file.readLine()) != null) { String fields[] = record.split(","); records.add(fields); } file.close(); return records; } @Test public void testFacebookRegistration() throws Exception { WebDriverWait wait = new WebDriverWait(driver, 20); try { wait.until(ExpectedConditions.elementToBeClickable(By .xpath("//*[@id='u_0_1']"))); } catch (TimeoutException ex) { Assert.fail("Not loaded"); } // set first name WebElement fname = driver.findElement(By.xpath("//*[@id='u_0_1']")); fname.click(); fname.clear(); fname.sendKeys(firstName); // set last name WebElement lname = driver.findElement(By.xpath("//*[@id='u_0_3']")); lname.click(); lname.clear(); lname.sendKeys(lastName); // set email WebElement emailAddress = driver.findElement(By .xpath("//*[@id='u_0_5']")); emailAddress.click(); emailAddress.clear(); emailAddress.sendKeys(email); // set email WebElement emailAddress2 = driver.findElement(By .xpath("//*[@id='u_0_8']")); emailAddress2.click(); emailAddress2.clear(); emailAddress2.sendKeys(email); // set password WebElement pass = driver.findElement(By.xpath("//*[@id='u_0_a']")); pass.click(); pass.clear(); pass.sendKeys(password); // click to Sign Up WebElement reg = driver.findElement(By.xpath("//*[@id='u_0_i']")); reg.click(); try { WebDriverWait wait2 = new WebDriverWait(driver, 10); wait2.until(ExpectedConditions.visibilityOfElementLocated(By .cssSelector("#u_0_f i.sx_2bac47"))); } catch (NoSuchElementException e) { Assert.fail("The element is not appeared."); } } }
When the test is executed, for each row in the test data collection, the test runner will be passing the test data as parameters to the dataDrivenJUnitTestWithCSV class constructor. It will then execute all the tests in the dataDrivenJUnitTestWithCSV class.
Instance variables are declared to store the test data passed by the test runner:
private String firstName;
private String lastName;
private String email;
private String password;
In the test case class constructor, these variables are assigned with values at runtime by the test runner from the test data collection.
In the testFacebookRegistration() method, we passed these variables to the Selenium WebDriver.
JUnit will display results for each set of test data as shown in the following screenshot:
Similar Posts from the author:
- Creating a data-driven test with JUnit
- Parameterized JUnit tests with Selenium WebDriver
- How to read text from PDF file using Java and Selenium Webdriver
- How to count number of images available on a web page then download them using selenium webdriver?
- How to use TestNG with Selenium WebDriver
2 thoughts to “Reading test data from a CSV file using JUnit”
Thanks so much. This saves my day!
I get error
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Comments are closed.