Road to data driven testing in webdriver java TestNg Part 2

In my previous two post, I have posted two approaches for data driven testing using java webdriver one for using testNG and another without testNg using excel file.

1. Data driven testing using java webdriver TestNg framework.
2. Road to data driven testing in webdriver java Part 1

In this post I am going to show you, how to perform data driven testing in webdriver with testNG framework using data from external excel file. I am continuing from my previous post “Road to data driven testing in webdriver java Part 1

I have created below java file using TestNg data provider annotation for the same data which I have used in my previous post Road to data driven testing in webdriver java Part 1.
package com.webdriver.test;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class NavigateURL {

       private WebDriver driver;
       private String baseUrl;

       @DataProvider(name = "myTest")
        public Object[][] createData1() {

                  ReadXLS readXls = new ReadXLS();
                  List dataList = readXls.getData();
                  Object obj[][] = new Object[dataList.size()][2];
                  for (int i = 1; i < dataList.size(); i++) {
                         String[] test = (String[]) dataList.get(i);
                         String countryName = test[0];
                         String countryDesc = test[1];
                         obj[i][0] = countryName;
                         obj[i][1] = countryDesc;
                  }
                  return obj;                     
         }

        @BeforeSuite
         public void setUp() throws Exception {
                    driver = new FirefoxDriver();
                    baseUrl = "http://www.wikipedia.org/";
                    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
           }

         @Test(dataProvider = "myTest")
         public void testSearchCountry(String country, String desc) throws Exception {
                    driver.get(baseUrl + "/wiki/Main_Page");
                    driver.findElement(By.id("searchInput")).clear();
                    driver.findElement(By.id("searchInput")).sendKeys(country);
                    driver.findElement(By.id("searchButton")).click();
                    String str = driver.findElement(
                                         By.xpath("//h1[@id='firstHeading']/span")).getText();
                    System.out.println(desc);
                    Assert.assertTrue(str.contains(country));
            }
                   

          @AfterSuite
          public void tearDown() throws Exception {
                    driver.quit();
           }
}


Run above test you should see that test will execute separate for each set of data. Failed test for any set of data does not impact on other data set.



29 comments:

  1. Let me know if you have any query...

    ReplyDelete
    Replies
    1. The code is really working fine now for data driven testing.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. I need to start with keyword driven testing in my project, but I am stuck with, where to start from.

      Thanks
      Kapish
      nayanbkec@yahoo.com

      Delete
    4. what is the format of data uve given in excel....give the snaphot of excel file for reference

      Delete
  2. The codes with heading "Road to data driven testing in webdriver java TestNg Part 2" and "Road to data driven testing in webdriver java TestNg Part 1" are not working.

    Thanks
    Kapish
    nayanbkec@yahoo.com

    ReplyDelete
  3. What type of error you are getting. did you add all required jar file.

    ReplyDelete
  4. Yes I have imported the jar files :
    1. Selenium 2.32.0
    2. poi-3.9
    and chromedriver.exe

    "Road to data driven testing in webdriver java TestNg Part 1" is giving output as "passed : testSearchCountry" and nothing, its not automating.

    and

    "Road to data driven testing in webdriver java TestNg Part 2" is throwing error as "FAILED: testSearchCountry(null, null)
    org.openqa.selenium.WebDriverException: unknown error: keys should be a string"

    Thanks
    Kapish

    ReplyDelete
  5. Are you passing correct data xls file? I guess that your are missing some thing so that unable to read data from xls file.

    I am sending a zip file for same scripts into your email ID just add required jars file and execute script.

    ReplyDelete
    Replies
    1. The script worked very well. Thanks for guiding.

      Thank you very much

      Delete
    2. wanted some guidance on keyword-driven testing in webdriver using java + testNG + apache poi.

      Searched lot on internet but got confused - how to start , how many files needed to to be created

      Thanks & regards
      Kapish Kumar

      Delete
    3. Before some time I have created keyword driven webdriver framework but I have not used TestNG, executed all test methods using java main method by handling exception.
      I will work on same and definitely will post on my blog.

      Thanks for reading my blog

      Delete
  6. how to configure datadriven framework under eclipse .??????i mean where to place the property file and all.???

    ReplyDelete
    Replies
    1. Hello Sagar

      If you follow each step of above post then you will be setup and create data driven webdriver test. you can put your data file where you need but best way to create a data folder at the root of your eclipse project and put there.

      Delete
  7. Please send me the scripts for reading the excel file
    my email id is janak.315@gmail.com

    ReplyDelete
    Replies
    1. What issue you are facing to implement from this post ?

      Delete
  8. U said u are reading data from XL sheet but where is the XL sheet path?
    i mean from where it is taking data?

    ReplyDelete
  9. You need to read post "Road to data driven testing in webdriver java Part 1” before this. I have not repeated "ReadXLS.java" class or sheet in this post. I have just mentioned link in this post. You click on mentioned link or you can go through below link.

    http://roadtoautomation.blogspot.in/2013/06/road-to-data-driven-testing-in.html

    ReplyDelete
    Replies
    1. Thank you very much. but when test fails i will not know for which set of data my test fails. how to over come this?

      Delete
    2. As you see in above screen shot log is generated for each set of data. Also it will show you in read mark for that set of data if failed.

      Delete
    3. Hi Below is my requirement. please give your suggestion.

      i am reading data from XL Workbook for this i have created a dataprovider is separate class and calling that in my actual test script where data is to be read.
      now i want to pass the sheet name from the test script to the dataprovider class so that same XL workbook can be used across all my test scripts.

      Delete
    4. Hi

      You can pass XL sheet using constructor of class.

      I requested you to comment with your identity such as google Id.

      Delete
  10. i am passing path and sheet name using constructor though it is reading data but my test script is skipped. i am getting below error.please provide me solution.

    Some DataProvider public static java.util.Iterator TestData.TestData_DataProvider.createData(java.lang.String,java.lang.String) throws java.io.IOException parameters unresolved: at 1 type class java.lang.String
    at 2 type class java.lang.String

    Below is the code

    //sample.java (test script)-- one class
    //Static.java(dataprovider) -- separate class


    public class Sample
    {
    private WebDriver driver;
    private String baseUrl;
    public Sample() throws IOException
    {
    try {
    Staticdata.createData("C:/WebDriverScripts/CIMA/src/TestData/CIMAData.xls","usernamelookup");

    }

    catch(Exception ioe) {
    //ioe.printStackTrace();
    }
    }

    @BeforeMethod
    public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.gmail.com";
    driver.get(baseUrl);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }
    @AfterMethod
    public void tearDown() throws Exception {
    driver.quit();
    }


    @Test(dataProvider = "TestData",dataProviderClass= Staticdata.class)
    public void test_verifyData1(String n1,String n2) {
    // WebDriver driver = new FirefoxDriver();
    //driver.get("http://www.gmail.com");
    WebElement userName = driver.findElement(By.name("Email"));
    userName.sendKeys(n1);
    WebElement password = driver.findElement(By.name("Passwd"));
    password.sendKeys(n2);
    WebElement signin = driver.findElement(By.name("signIn"));
    signin.click();
    String expectedTitle = "Gmail";
    String actualTitle = driver.getTitle();
    AssertJUnit.assertEquals(actualTitle, expectedTitle);
    System.out.println(n1+" "+n2); }
    }


    //Data provider
    public class Staticdata {
    @DataProvider (name="TestData")
    public static Iterator createData(String path, String sheetname) throws IOException{
    ArrayList myEntries = new ArrayList();
    File inputWorkbook = new File(path);
    Workbook w;
    String Temp1, Temp2;
    try {
    w = Workbook.getWorkbook(inputWorkbook);
    Sheet sheet = w.getSheet(sheetname);
    for (int i = 1; i < sheet.getRows(); i++) {
    // column, row
    Cell cell = sheet.getCell(0, i);
    Temp1 = cell.getContents();
    cell = sheet.getCell(1, i);
    Temp2 = cell.getContents();
    myEntries.add(new Object [] {Temp1,Temp2});
    }
    }
    catch (BiffException e)
    {e.printStackTrace();}
    System.out.println("Successfully read data file");
    return myEntries.iterator();
    }
    }

    ReplyDelete
  11. This code works perfect but if one of my column is numeric, it does not read the same. It throws an error. Can you please let me know a way to read both string and numeric values from excel

    ReplyDelete
    Replies
    1. it is because cell type is not verified.
      you can check it in your code for it.

      switch(cell.getCellType()) {
      case Cell.CELL_TYPE_BOOLEAN:
      System.out.print(cell.getBooleanCellValue() + "\t\t");
      break;
      case Cell.CELL_TYPE_NUMERIC:
      System.out.print((int)cell.getNumericCellValue() + "\t\t");
      break;
      case Cell.CELL_TYPE_STRING:
      System.out.print(cell.getStringCellValue() + "\t\t");
      break;
      }

      Delete
  12. Please send me any of your application scripts for reading the excel file, so that i can modify it to my s/w needs.
    my email id is spradeep89@gmail.com

    ReplyDelete
  13. Thanks to sharing this informative post.This code works perfect.

    ReplyDelete
  14. Even though i changed the correct path and still i am getting null value for country , but its reading
    String countryName = test[0];
    String countryDesc = test[1];
    am seeing the value but the next line it shows null while debugging.

    what could be the issue

    ReplyDelete
  15. Its really good...But having a doubt that if I want to execute number of test cases by calling diifernet methods .
    how can I do it?
    Ex: if I need to execute 10 test cases by calling 3 or 4 different methods for each test case how can I do that?

    can you please provide me the sample code
    Thanks in Advance
    annils@ymail.com

    ReplyDelete

Leave your comments, queries, suggestion I will try to provide solution