Friday, 21 October 2011

Example - Data driven test using a csv text file

Aim:Data driven example using CSV ( Comma Separated Variable) file and Selenium 2. The example demonstrates adding new posts to the wordpress test site via the csv file. Test data data can be added to the csv file.


Difficulty Level: High

Prerequisites:
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, linkText, cssSelector and xpath
  • clear()
  • sendkeys()
  • click()
  • random string
Steps in implementation:
  1. Download and Install Eclipse IDE using link http://www.eclipse.org/downloads/.     
  2. Tip: download the version suitable for your PC ( 32 bit/64bit))
  3. Download the Selenium2 API 'selenium-server-standalone-*.jar' library using link http://seleniumhq.org/download
  4. No need to get JUnit jar file in separate as it is inbuilt in  'selenium-server-standalone-*.jar'.
  5. Download and save the file as selenium.csv in C: drive from here
  6. Launch the Eclipse IDE.
  7. Create a new Java project and name it FirstExample. You will see a default folder 'src' inside it.
  8. Do right click on the created project and select Build Path >> Configuration Build Path.
  9. Add 'selenium-server-standalone-*.jar' under Libraries tab by clicking 'Add External Jars'.
  10. Add downloaded "javacsv-2.0.jar"  under Libraries tab by clicking 'Add External Jars'.
  11. Right click on 'src' and add a package 'com.example.tests'.
  12. Create  java classes  'DataDriven.java ' into the created package.
  13. Paste the below mentioned two script in corresponding java files.
  14. Right click 'DataDriven.java' and click 'Run as >> JUnit test'.
  15. During the execution you would see that created post title is read from the CSV file.



Scripts:

package com.example.tests;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.csvreader.CsvReader;
import java.util.Random;

public class DataDriven {

private WebDriver driver;private StringBuffer verificationErrors = new StringBuffer();

public String browser,url,username,password,post_title,Exc_erpt,URL1,Custom_name,Test_value,category_name;

{
try {CsvReader csvdata = new CsvReader("C:\\selenium.csv");

csvdata.readHeaders();

while (csvdata.readRecord())
{
url      = csvdata.get("URL");
username = csvdata.get("Username");
password = csvdata.get("Password");
post_title = csvdata.get("post title");
Exc_erpt = csvdata.get("Excerpt");
URL1=csvdata.get("URL1");
Custom_name=csvdata.get("Cuname");
Test_value=csvdata.get("Tvalue");
category_name=csvdata.get("CName");
}
csvdata.close();
} catch (Exception e) {}}

@Before
public void setUp() throws Exception {

driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);}
@Test
public void testDataDriven() throws Exception {
driver.get(url);
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys(username);
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys(password);
driver.findElement(By.id("wp-submit")).click();
for (int second = 0;; second++) {if (second >= 60) fail("timeout");
try { if (isElementPresent(By.xpath("//div[@id='user_info']/p/a[2]"))) break; }
catch (Exception e) {}Thread.sleep(1000);
}
driver.findElement(By.linkText("Posts")).click();
for (int second = 0;; second++) {if (second >= 60) fail("timeout");
try { if (isElementPresent(By.xpath("//div[@id='wpbody-content']/div[3]/h2"))) break;
} catch (Exception e) {}Thread.sleep(1000);
}
driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).clear();
int a=new Random().nextInt(123456789);
String post_name= post_title+a;driver.findElement(By.id("title")).sendKeys(post_name);
driver.findElement(By.id("excerpt")).clear();
driver.findElement(By.id("excerpt")).sendKeys(Exc_erpt);
driver.findElement(By.id("trackback_url")).clear();
driver.findElement(By.id("trackback_url")).sendKeys(URL1);
driver.findElement(By.id("addmetasub")).click();
driver.findElement(By.id("metavalue")).clear();
driver.findElement(By.id("metavalue")).sendKeys(Test_value);
driver.findElement(By.id("addmetasub")).click();
driver.findElement(By.id("category-add-toggle")).click();
driver.findElement(By.id("newcategory")).clear();
driver.findElement(By.id("newcategory")).sendKeys(category_name);
driver.findElement(By.id("newcategory_parent")).sendKeys("Android Development");
driver.findElement(By.id("category-add-submit")).click();
driver.findElement(By.id("publish")).click();}
@After
public void tearDown() throws Exception
{
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {fail(verificationErrorString);}}
private boolean isElementPresent(By by)
{
try {driver.findElement(by);
return true;
}
catch (NoSuchElementException e)
{return false;
}
}
}


Helpful Video:

6 comments:

  1. I get an error on line 19 about escaped character.

    I believe the single / should be // to escape the character.

    ReplyDelete
  2. I'm getting a compile error as follows :

    java.lang.NoClassDefFoundError: com/google/common/base/Function
    at com.example.tests.DataDriven.setUp(DataDriven.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)


    Vipin, can we fix this before Monday ?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Exception says that you havn't included all the Selenium 2 API Jars and I have updated the Script..

    ReplyDelete
  5. Ok great. I was missing the Selenium Server jar. This one is now working.

    ReplyDelete
  6. In this example we did read data from an external CSV file and did use it in our scenario script. So basically in summary we were using the test data for the script scenario from the external CSV file.

    Basic Steps:
    • Create a CSV file and write some data
    • Create java script and using the Code connect with the external created CSV
    • Store the data from CSV to any variable
    • Now type the same saved variable into an input field in the java selenium script.

    ReplyDelete