Data provider with excel

Data-Driven Testing

A key benefit of automating functional testing is the ability to test large volumes of data on the system quickly. But you must be able to manipulate the data sets, perform calculations, and quickly create hundreds of test iterations and permutations with minimal effort. Test Automation Frameworks must-have capability to integrate with spreadsheets and provide powerful calculation features.

Apache POI (Excel)

Most commercial automated software tools on the market support some sort of data-driven testing, which allows you to automatically run a test case multiple times with different input and validation values. As Selenium Webdriver is more an automated testing framework than a ready-to-use tool, you will have to put in some effort to support data-driven testing in your automated tests. I usually prefer to use Microsoft Excel as the format for storing my parameters. An additional advantage of using Excel is that you can easily outsource the test data administration to someone other than yourself, someone who might have better knowledge of the test cases that need to be run and the parameters required to execute them.

TestNG Data Providers

When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc…), in such cases parameters can be passed using Dataproviders. A Data Provider is a method annotated with @DataProvider. A Data Provider returns an array of objects.

Let us check out the same Sign In examples using Data Providers with an Excel datasheet.

How to do it…

Here we will follow a simple step by step process to Implement Excel with TestNg Data Provider.

Step 1: Create a test case of Login Application with TestNG Data Provider.

Step 2Create a Test Datasheet.

Step 3: Create functions to Open & Read data from Excel

Step 4: Create a TestNg test case for accepting data from Excel using Data Provider.

Step 5: Run the test against the Test Case name in the Test Data file.

Step 1: Create a test case of LogIn Application with TestNG Data Provider

  1. Create a TestNG class ‘DataProviderTest‘ by Pressing Ctrl+N, select ‘Create TestNG Class‘ under TestNG category and Under Annotations, check ‘DataProvider‘ and click Finish.

  2. By default, the DataProvider name is ‘dp‘, change it to ‘Authentication‘. This method returns array of object array.

  3. Add a method Registration_data() to your Test class. This method takes two strings as input parameters.

  4. Write script for LogIn Application under method @Test.

Test Case will look like this:

package automationFramework;

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.DataProvider;

import org.testng.annotations.Test;

public class DataProviderTest {

    private static WebDriver driver;

  @DataProvider(name = "Authentication")

  public static Object[][] credentials() {

        // The number of times data is repeated, test will be executed the same no. of times

        // Here it will execute two times

        return new Object[][] { { "testuser_1", "[email protected]" }, { "testuser_1", "[email protected]" }};

  }

  // Here we are calling the Data Provider object with its Name

  @Test(dataProvider = "Authentication")

  public void test(String sUsername, String sPassword) {

      driver = new FirefoxDriver();

      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      driver.get("https://www.store.demoqa.com");

      driver.findElement(By.xpath(".//*[@id='account']/a")).click();

      // Argument passed will be used here as String Variable

      driver.findElement(By.id("log")).sendKeys(sUsername);

      driver.findElement(By.id("pwd")).sendKeys(sPassword);

      driver.findElement(By.id("login")).click();

      driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

      driver.quit();

  }

}

Step 2:  Create a Test Datasheet

  1. Create a ‘New Package‘ file and name it as ‘testData’, by right click on the Project and select New > Package. I always place my Test Data file under a separate test data folder.

  2. Place an Excel file in the above-created package location and save it as TestData.xlsx. Fill the data in the excel like below image:
    TestNG Data Provider with Excel

Step 3: Create functions to Open & Read data from Excel

We need a way to open this Excel sheet and read data from it within our Selenium test script. For this purpose, I use the Apache POI library, which allows you to read, create and edit Microsoft Office-documents using Java. The classes and methods we are going to use to read data from Excel sheet are located in the org.apache.poi.hssf.usermodel package.

To see step by step process to set up Apache POI Excel, please visit Data-Driven Framework.

package utility;

        import java.io.FileInputStream;

		import java.io.FileNotFoundException;

		import java.io.FileOutputStream;

		import java.io.IOException;

		import org.apache.poi.xssf.usermodel.XSSFCell;

		import org.apache.poi.xssf.usermodel.XSSFRow;

		import org.apache.poi.xssf.usermodel.XSSFSheet;

		import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ExcelUtils {

			private static XSSFSheet ExcelWSheet;

			private static XSSFWorkbook ExcelWBook;

			private static XSSFCell Cell;

			private static XSSFRow Row;

		public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {   

		   String[][] tabArray = null;

		   try {

			   FileInputStream ExcelFile = new FileInputStream(FilePath);

			   // Access the required test data sheet

			   ExcelWBook = new XSSFWorkbook(ExcelFile);

			   ExcelWSheet = ExcelWBook.getSheet(SheetName);

			   int startRow = 1;

			   int startCol = 1;

			   int ci,cj;

			   int totalRows = ExcelWSheet.getLastRowNum();

			   // you can write a function as well to get Column count

			   int totalCols = 2;

			   tabArray=new String[totalRows][totalCols];

			   ci=0;

			   for (int i=startRow;i<=totalRows;i++, ci++) {           	   

				  cj=0;

				   for (int j=startCol;j<=totalCols;j++, cj++){

					   tabArray[ci][cj]=getCellData(i,j);

					   System.out.println(tabArray[ci][cj]);  

						}

					}

				}

			catch (FileNotFoundException e){

				System.out.println("Could not read the Excel sheet");

				e.printStackTrace();

				}

			catch (IOException e){

				System.out.println("Could not read the Excel sheet");

				e.printStackTrace();

				}

			return(tabArray);

			}

		public static String getCellData(int RowNum, int ColNum) throws Exception {

			try{

				Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);

				int dataType = Cell.getCellType();

				if  (dataType == 3) {

					return "";

				}else{

					String CellData = Cell.getStringCellValue();

					return CellData;

				}catch (Exception e){

				System.out.println(e.getMessage());

				throw (e);

				}

			}

	}

Step 4: Create a TestNg test case for accepting data from Excel using Data Provider

  1. Create a TestNG class ‘DataProviderWithExcel‘ by Pressing Ctrl+N , select ‘Create TestNG Class‘ under TestNG category and Under Annotations, check @BeforeMethod, @AfterMethod & DataProvider and click Finish.

  2. Add a method Registration_data() to your Test class. This method takes two strings as input parameters.

  3. Now divide the test case into three parts :

  • @BeforeMethod : Launch Firefox and direct it to the Base URL
  • @Test : Enter Username & Password to Login, Print console message and Log out
  • @AfterMethod : Close Firefox browser

Test Case will look like this:

package practiceTestCases;

		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.AfterMethod;

		import org.testng.annotations.BeforeMethod;

		import org.testng.annotations.Test;

		import org.testng.annotations.DataProvider;

		import utility.ExcelUtils;

	public class DataProviderWithExcel_001 {

		WebDriver driver;

	    @BeforeMethod

	    public void beforeMethod() throws Exception {

		    driver = new FirefoxDriver();

	        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

	        driver.get("https://www.store.demoqa.com");	 

		}

	@Test(dataProvider="Authentication")

    public void Registration_data(String sUserName,String sPassword)throws  Exception{

        driver.findElement(By.xpath(".//*[@id='account']/a")).click();

        driver.findElement(By.id("log")).sendKeys(sUserName);

		System.out.println(sUserName);

        driver.findElement(By.id("pwd")).sendKeys(sPassword);

		System.out.println(sPassword);

        driver.findElement(By.id("login")).click();

        System.out.println(" Login Successfully, now it is the time to Log Off buddy.");

        driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

		}

    @DataProvider

    public Object[][] Authentication() throws Exception{

         Object[][] testObjArray = ExcelUtils.getTableArray("D://ToolsQA//OnlineStore//src//testData//TestData.xlsx","Sheet1");

         return (testObjArray);

		}

    @AfterMethod

    public void afterMethod() {

  	    driver.close();

    	}

}

Note: This LogIn test will execute two times as there are two users credentials in data provider Array.

Step 5: Run the test against the Test Case name in the Test Data file

  1. This means that your test should be run once only with the data which is mentioned against the Test Case name. To do this we need to tweak the Excel utility class, plus need to add few more function to fetch out the current Test Case name & the row number which contain the Test Case name.
package utility;

		import java.io.FileInputStream;

		import java.io.FileNotFoundException;

		import java.io.FileOutputStream;

		import java.io.IOException;

		import org.apache.poi.xssf.usermodel.XSSFCell;

		import org.apache.poi.xssf.usermodel.XSSFRow;

		import org.apache.poi.xssf.usermodel.XSSFSheet;

		import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ExcelUtils {

			private static XSSFSheet ExcelWSheet;

			private static XSSFWorkbook ExcelWBook;

			private static XSSFCell Cell;

			private static XSSFRow Row;

		//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method

		public static void setExcelFile(String Path,String SheetName) throws Exception {

			   try {

					// Open the Excel file

					FileInputStream ExcelFile = new FileInputStream(Path);

					// Access the required test data sheet

					ExcelWBook = new XSSFWorkbook(ExcelFile);

					ExcelWSheet = ExcelWBook.getSheet(SheetName);

					} catch (Exception e){

						throw (e);

					}

			}

		public static Object[][] getTableArray(String FilePath, String SheetName, int iTestCaseRow)    throws Exception

		{   

		   String[][] tabArray = null;

		   try{

			   FileInputStream ExcelFile = new FileInputStream(FilePath);

			   // Access the required test data sheet

			   ExcelWBook = new XSSFWorkbook(ExcelFile);

			   ExcelWSheet = ExcelWBook.getSheet(SheetName);

			   int startCol = 1;

			   int ci=0,cj=0;

			   int totalRows = 1;

			   int totalCols = 2;

			   tabArray=new String[totalRows][totalCols];

				   for (int j=startCol;j<=totalCols;j++, cj++)

				   {

					   tabArray[ci][cj]=getCellData(iTestCaseRow,j);

					   System.out.println(tabArray[ci][cj]);

				   }

			}

			catch (FileNotFoundException e)

			{

				System.out.println("Could not read the Excel sheet");

				e.printStackTrace();

			}

			catch (IOException e)

			{

				System.out.println("Could not read the Excel sheet");

				e.printStackTrace();

			}

			return(tabArray);

		}

		//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num

		public static String getCellData(int RowNum, int ColNum) throws Exception{

		   try{

			  Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);

			  String CellData = Cell.getStringCellValue();

			  return CellData;

			  }catch (Exception e){

				return"";

				}

			}

		public static String getTestCaseName(String sTestCase)throws Exception{

			String value = sTestCase;

			try{

				int posi = value.indexOf("@");

				value = value.substring(0, posi);

				posi = value.lastIndexOf(".");	

				value = value.substring(posi + 1);

				return value;

					}catch (Exception e){

				throw (e);

						}

			}

		public static int getRowContains(String sTestCaseName, int colNum) throws Exception{

			int i;

			try {

				int rowCount = ExcelUtils.getRowUsed();

				for ( i=0 ; i<rowCount; i++){

					if  (ExcelUtils.getCellData(i,colNum).equalsIgnoreCase(sTestCaseName)){

						break;

					}

				}

				return i;

					}catch (Exception e){

				throw(e);

				}

			}

		public static int getRowUsed() throws Exception {

				try{

					int RowCount = ExcelWSheet.getLastRowNum();

					return RowCount;

				}catch (Exception e){

					System.out.println(e.getMessage());

					throw (e);

				}

			}

}

Final Test Case

  1. Get the Test Case name.

  2. With the Test Case name, get the row number of the Excel sheet for the test.

  3. Get the data from the excel sheet for the fetched test row.

package practiceTestCases;

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.Test;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.DataProvider;

import utility.ExcelUtils;

public class DataProviderWithExcel_002 {

	private String sTestCaseName;

	private int iTestCaseRow;

	WebDriver driver;

  @BeforeMethod

  public void beforeMethod() throws Exception {

	  driver = new FirefoxDriver();

      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      driver.get("https://www.store.demoqa.com");	 

  }	

  @Test(dataProvider = "Authentication")

  public void f(String sUserName, String sPassword) {

	    driver.findElement(By.xpath(".//*[@id='account']/a")).click();

	    driver.findElement(By.id("log")).sendKeys(sUserName);

		System.out.println(sUserName);

	    driver.findElement(By.id("pwd")).sendKeys(sPassword);

		System.out.println(sPassword);

	    driver.findElement(By.id("login")).click();

	    System.out.println(" Login Successfully, now it is the time to Log Off buddy.");

	    driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

  }

  @AfterMethod

  public void afterMethod() {

	   driver.close();

  }

  @DataProvider

  public Object[][] Authentication() throws Exception{

	    // Setting up the Test Data Excel file

	 	ExcelUtils.setExcelFile("D://ToolsQA//OnlineStore//src//testData//TestData.xlsx","Sheet1");

	 	sTestCaseName = this.toString();

	  	// From above method we get long test case name including package and class name etc.

	  	// The below method will refine your test case name, exactly the name use have used

	  	sTestCaseName = ExcelUtils.getTestCaseName(this.toString());

	    // Fetching the Test Case row number from the Test Data Sheet

	    // Getting the Test Case name to get the TestCase row from the Test Data Excel sheet

	 	iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,0);

	    Object[][] testObjArray = ExcelUtils.getTableArray("D://ToolsQA//OnlineStore//src//testData//TestData.xlsx","Sheet1",iTestCaseRow);

	    	return (testObjArray);

		}

}

NoteThis will just execute your test once against the current est case data.

In this example we will see how to pass the data to Dataproviders by reading the data from excel sheet. DataProvider helps to send multiple sets of data to a test method. But here we need to make sure that the array returned by the dataprovider should match with the test method parameters.

We will write a simple program in which we will validate login screen by taking multiple usernames and passwords. The annotated method must return object[][] where each object[] can be assigned to the test method one as username and the other parameter as password.

Step 1: First create a method to read excel data and return string array.
Step 2: Create before class and after class methods which helps in getting the browser and closing them when done.
Step 3: Create a data provider which actually gets the values by reading the excel.
Step 4: Create a Test which takes two parameters username and password.
Step 5: Add dataprovider name for @Test method to receive data from dataprovider.

package com.pack;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.testng.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;


import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcelDataProvider {
	public WebDriver driver;
	public WebDriverWait wait;
	String appURL = "https://www.linkedin.com/";
	
	//Locators
	private By byEmail = By.id("session_key-login");
	private By byPassword = By.id("session_password-login");
	private By bySubmit = By.id("signin");
	private By byError = By.id("global-alert-queue");
	
	@BeforeClass
	public void testSetup() {
		driver=new FirefoxDriver();
		driver.manage().window().maximize();
		wait = new WebDriverWait(driver, 5);
	}
	

	@Test(dataProvider="empLogin")
	public void VerifyInvalidLogin(String userName, String password) {
		driver.navigate().to(appURL);
		driver.findElement(byEmail).sendKeys(userName);
		driver.findElement(byPassword).sendKeys(password);
		//wait for element to be visible and perform click
		wait.until(ExpectedConditions.visibilityOfElementLocated(bySubmit));
		driver.findElement(bySubmit).click();
		
		//Check for error message
		wait.until(ExpectedConditions.presenceOfElementLocated(byError));
		String actualErrorDisplayed = driver.findElement(byError).getText();
		String requiredErrorMessage = "Please correct the marked field(s) below.";
		Assert.assertEquals(requiredErrorMessage, actualErrorDisplayed);
		
	}
	
	@DataProvider(name="empLogin")
	public Object[][] loginData() {
		Object[][] arrayObject = getExcelData("D:/sampledoc.xls","Sheet1");
		return arrayObject;
	}

	/**
	 * @param File Name
	 * @param Sheet Name
	 * @return
	 */
	public String[][] getExcelData(String fileName, String sheetName) {
		String[][] arrayExcelData = null;
		try {
			FileInputStream fs = new FileInputStream(fileName);
			Workbook wb = Workbook.getWorkbook(fs);
			Sheet sh = wb.getSheet(sheetName);

			int totalNoOfCols = sh.getColumns();
			int totalNoOfRows = sh.getRows();
			
			arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
			
			for (int i= 1 ; i < totalNoOfRows; i++) {

				for (int j=0; j < totalNoOfCols; j++) {
					arrayExcelData[i-1][j] = sh.getCell(j, i).getContents();
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		}
		return arrayExcelData;
	}

	@Test
	public void tearDown() {
		driver.quit();
	}
}

After clicking on login button, we are using WebdriverWaits to Check for error message and validate.

The output should look like below:

[TestNG] Running:
  C:UserseasyAppDataLocalTemptestng-eclipse-583753747testng-customsuite.xml

PASSED: VerifyInvalidLogin("testuser1", "testpassword1")
PASSED: VerifyInvalidLogin("testuser2", "testpassword2")
PASSED: VerifyInvalidLogin("testuser3", "testpassword3")
PASSED: VerifyInvalidLogin("testuser4", "testpassword4")
PASSED: VerifyInvalidLogin("testuser5", "testpassword5")

===============================================
    Default test
    Tests run: 5, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 5, Failures: 0, Skips: 0
===============================================

@Test //Test method

(dataProvider=«ReadVariant») //It get values from ReadVariant function method

//Here my all parameters from excel sheet are mentioned.

public void AddVariants(String NAME, String DESCRIPTION, String WEIGHT, String PRICE, String MODEL, String RS) throws Exception

{

Data will set in Excel sheet once one parameter will get from excel sheet to Respective locator position.

DataSet++;

System.out.println(«NAme of product available are:» +NAME);

System.out.println(«Weight for products are:» +DESCRIPTION);

System.out.println(«Volume of product are:» +WEIGHT);

System.out.println(«Description quotation are:» +PRICE);

System.out.println(«Description picklings are:» +MODEL);

WebDriverWait wait =  new WebDriverWait(driver, 90);

// User get Login

driver.get(«http://192.168.1.91/user/login»);

driver.findElement(By.id(«prependedInput»)).sendKeys(«admin»);

driver.findElement(By.id(«prependedInput2»)).sendKeys(«admin»);

driver.findElement(By.id(«_submit»)).click();

Thread.sleep(4000);

// Click on product label

WebElement element1 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(«//a[@href =’#/enrich/product/’]»)));

driver.findElement(By.xpath(«//a[@href =’#/enrich/product/’]»)).click();

Thread.sleep(2000);

//click on create product

driver.findElement(By.cssSelector(«div[data-drop-zone=’buttons’] a»)).click();

//click on product model

driver.findElement(By.cssSelector(«[data-form=’pim-product-create-modal’]»)).click();

Thread.sleep(6000);

//click on SKU and passed data from dataprovider i.e MODEL

driver.findElement(By.name(«identifier»)).sendKeys(MODEL);

//Thread.sleep(6000);

// Select family of product

WebElement element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(«/html/body/div[17]/div[2]/div/div/div[2]/div[3]/div[2]/div[2]/div/a»)));

driver.findElement(By.xpath(«/html/body/div[17]/div[2]/div/div/div[2]/div[3]/div[2]/div[2]/div/a»)).click();

Thread.sleep(2000);

//driver.findElement(By.xpath(«/html/body/div[19]/ul/li[1]»)).click();

//click on save

driver.findElement(By.xpath(«/html/body/div[17]/div[3]/a[2]»)).click();

Thread.sleep(8000);

WebElement element3 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(«div[data-attribute=’name’] input»)));

//click on name input field and clear .

driver.findElement(By.cssSelector(«div[data-attribute=’name’] input»)).clear();

//Send Name parameter from dataprovider

driver.findElement(By.cssSelector(«div[data-attribute=’name’] input»)).sendKeys(NAME);

//clear description field

driver.findElement(By.className(«note-editable»)).clear();

//send description parameter from data provider

driver.findElement(By.className(«note-editable»)).sendKeys(DESCRIPTION);

//clear weight field

driver.findElement(By.cssSelector(«div[data-attribute=’weight’] input»)).clear();

//send weight parameter from data provider

driver.findElement(By.cssSelector(«div[data-attribute=’weight’] input»)).sendKeys(WEIGHT);

//send price parameter from data provider

driver.findElement(By.cssSelector(«div[data-attribute=’main_price’] input»)).sendKeys(PRICE);

Thread.sleep(4000);

driver.findElement(By.xpath(«/html/body/div[1]/div/div[3]/div/div[1]/div[2]/div[1]/header/div[1]/div[2]/div[1]/div[1]/div[2]/div[2]/div[3]/button»)).click();

//Result is equal to pass mentioned here

Res=«Pass»;

obj1.WriteResult(Res, DataSet+1); //It call write Result program and DataSet get increase by +1 after execution of write Result method

/* code for logout */

Thread.sleep(4000);

driver.findElement(By.xpath(«/html/body/div[1]/div/div[3]/div/div[1]/div[2]/div[1]/header/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div/div[1]/div[1]»)).click();

Thread.sleep(4000);

driver.findElement(By.xpath(«/html/body/div[1]/div/div[3]/div/div[1]/div[2]/div[1]/header/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div[3]»)).click();

//driver.findElement(By.cssSelector(«div[data-attribute=’Model_new’] input»)).sendKeys(MODEL);

}

Excel Spreadsheet Integration with .NET Apps

  • DataBind to Excel Spreadsheets using standard Visual Studio wizards.
  • Comprehensive support for CRUD (Create, Read, Update, and Delete) operations.
  • Use Excel Spreadsheets as simple real-time database to power .NET applications.

ADO.NET Provider Overview

The Excel ADO.NET Provider offers the most natural way to access Excel data from any .NET application. Simply use Excel Data Provider objects to connect and access data just as you would access any traditional database. You will be able to use the Excel Data Provider through Visual Studio Server Explorer, in code through familiar classes, and in data controls like DataGridView, GridView, DataSet, etc.

Using the Excel Data Provider

The Excel Data Provider wraps the complexity of accessing Excel services in an easy-to-integrate, fully managed ADO.NET Data Provider. Applications then access Excel through the Excel Data Provider with simple Transact-SQL.

The CData ADO.NET Provider for Excel hides the complexity of accessing data and provides additional powerful security features, smart caching, batching, socket management, and more.

Working with DataAdapters, DataSets, DataTables, etc.

The Excel Data Provider has the same ADO.NET architecture as the native .NET data providers for SQL Server and OLEDB, including: ExcelConnection, ExcelCommand, ExcelDataAdapter, ExcelDataReader, ExcelDataSource, ExcelParameter, etc. Because of this you can now access Excel data in an easy, familiar way.

More Than Read-Only: Full Update/CRUD Support

Excel Data Provider goes beyond read-only functionality to deliver full support for Create, Read Update, and Delete operations (CRUD). Your end-users can interact with the data presented by the Excel Data Provider as easily as interacting with a database table.

Driver Features

  • Fully managed .NET: 100% fully managed ADO.NET libraries supporting .NET Framework 2.0 and beyond.
  • Developer Friendly: Seamless integration with all versions of Visual Studio.
  • Powerful ADO.NET Features: Including support for ADO.NET Entity Framework (EF 5 & 6), ADO.NET 2.0, LINQ to Datasets, etc.
  • Replication and Caching: Our replication and caching commands make it easy to copy data to local and cloud data stores such as Oracle, SQL Server, Google Cloud SQL, etc. The replication commands include many features that allow for intelligent incremental updates to cached data.
  • String, Date, Numeric SQL Functions: The driver includes a library of 50 plus functions that can manipulate column values into the desired result. Popular examples include Regex, JSON, and XML processing functions.
  • Collaborative Query Processing: Our drivers enhance the data source’s capabilities by additional client side processing, when needed, to enable analytic summaries of data such as SUM, AVG, MAX, MIN, etc.
  • Easily Customizable and Configurable: The data model exposed by our ADO.NET Providers can easily be customized to add or remove tables/columns, change data types, etc. without requiring a new build. These customizations are supported at runtime using human-readable schema files that are easy to edit.
  • Secure Connectivity: Includes standard Enterprise-class security features such as TLS/ SSL data encryption for all client-server communications.

Contact us: 

Call: (800) 235-7250

Contact Us By Email

Online Documentation

When we want to create follow data driven approach and create a framework then best way is to use Excel to store our data and we can pass the Data as parameters using Data providers which we have seen in our previous post.

Step by step process to Implement Excel with TestNg Data Provider.

Step 1: Create a test case of Login Application with TestNG Data Provider.

Step 2:  Create a Test Data sheet.

Step 3: Create functions to Open & Read data from Excel

Step 4: Create a TestNg test case for accepting data from Excel using Data Provider.

Step 5: Run the test against the Test Case name in the Test Data file.

Read Data From Excel Sheet using Apache POI library —

Below is our code to open Excel sheet and read data from it within our Selenium test script. For this purpose, we are using the Apache POI library, which allows us to read, create and edit Microsoft Office-documents using Java. The classes and methods we are going to use to read data from Excel sheet are located in the org.apache.poi.hssf.usermodel.

1. Download the Apache POI  from the link http://poi.apache.org/ and add it in your project build path.

2. Use Below Code to read Data from Excel file.

package test;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

 private static XSSFSheet ExcelWSheet;

 private static XSSFWorkbook ExcelWBook;

 private static XSSFCell Cell;

 private static XSSFRow Row;

 public static void setExcelFile(String Path,String SheetName) throws Exception {
   
     try {

    // Open the Excel file

    FileInputStream ExcelFile = new FileInputStream(Path);

    // Access the required test data sheet

    ExcelWBook = new XSSFWorkbook(ExcelFile);

    ExcelWSheet = ExcelWBook.getSheet(SheetName);

    } catch (Exception e){

     throw (e);

    }

  }
 public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {

  String[][] tabArray = null;

  try {

   FileInputStream ExcelFile = new FileInputStream(FilePath);

   // Access the required test data sheet

   ExcelWBook = new XSSFWorkbook(ExcelFile);

   ExcelWSheet = ExcelWBook.getSheet(SheetName);

   int startRow = 1;

   int startCol = 1;

   int ci, cj;

   int totalRows = ExcelWSheet.getLastRowNum();

   // you can write a function as well to get Column count

   int totalCols = 2;

   tabArray = new String[totalRows][totalCols];

   ci = 0;

   for (int i = startRow; i <= totalRows; i++, ci++) {

    cj = 0;

    for (int j = startCol; j <= totalCols; j++, cj++) {

     tabArray[ci][cj] = getCellData(i, j);

     System.out.println(tabArray[ci][cj]);

    }

   }

  }

  catch (FileNotFoundException e) {

   System.out.println("Could not read the Excel sheet");

   e.printStackTrace();

  }

  catch (IOException e) {

   System.out.println("Could not read the Excel sheet");

   e.printStackTrace();

  }

  return (tabArray);

 }

 public static String getCellData(int RowNum, int ColNum) throws Exception {
 
   try{
 
    Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
 
    int dataType = Cell.getCellType();
 
    if  (dataType == 3) {
 
     return "";
 
    }else{
 
     String CellData = Cell.getStringCellValue();
 
     return CellData;
    }
 
    }catch (Exception e){
 
    System.out.println(e.getMessage());
 
    throw (e);
 
    }
 
   
 
  }
 public static String getTestCaseName(String sTestCase)throws Exception{
   
  String value = sTestCase;

  try{

   int posi = value.indexOf("@");

   value = value.substring(0, posi);

   posi = value.lastIndexOf("."); 

   value = value.substring(posi + 1);

   return value;

    }catch (Exception e){

   throw (e);

     }

  }

 public static int getRowContains(String sTestCaseName, int colNum) throws Exception{

  int i;

  try {

   int rowCount = ExcelUtils.getRowUsed();

   for ( i=0 ; i<rowCount; i++){

    if  (ExcelUtils.getCellData(i,colNum).equalsIgnoreCase(sTestCaseName)){

     break;

    }

   }

   return i;

    }catch (Exception e){

   throw(e);

   }

  }

 public static int getRowUsed() throws Exception {

   try{

    int RowCount = ExcelWSheet.getLastRowNum();

    return RowCount;

   }catch (Exception e){

    System.out.println(e.getMessage());

    throw (e);

   }

  }
 public static Object[][] getTableArray(String FilePath, String SheetName, int iTestCaseRow)    throws Exception
  
 {   

    String[][] tabArray = null;

    try{

     FileInputStream ExcelFile = new FileInputStream(FilePath);

     // Access the required test data sheet

     ExcelWBook = new XSSFWorkbook(ExcelFile);

     ExcelWSheet = ExcelWBook.getSheet(SheetName);

     int startCol = 1;

     int ci=0,cj=0;

     int totalRows = 1;

     int totalCols = 1;

     tabArray=new String[totalRows][totalCols];

      for (int j=startCol;j<=totalCols;j++, cj++)

      {

       tabArray[ci][cj]=getCellData(iTestCaseRow,j);

       System.out.println(tabArray[ci][cj]);

      }

  }

  catch (FileNotFoundException e)

  {

   System.out.println("Could not read the Excel sheet");

   e.printStackTrace();

  }

  catch (IOException e)

  {

   System.out.println("Could not read the Excel sheet");

   e.printStackTrace();

  }

  return(tabArray);

 }
    }

 3. Create excelfile with Data which we want to pass to our test case as parameter.

4. Update the Test case for using parameters from excel.

package test;


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
 
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
import org.testng.annotations.Test;
 
import org.testng.annotations.BeforeMethod;
 
import org.testng.annotations.AfterMethod;
 
import org.testng.annotations.DataProvider;
 

 
public class TestCaseExcelData {
 
 private String sTestCaseName;
 
 private int iTestCaseRow;
 
 WebDriver driver;
 
  @BeforeMethod
 
  public void beforeMethod() throws Exception {
 
   System.setProperty("webdriver.chrome.driver", "C:\Softwares\chromedriver_win32\chromedriver.exe");
  
   driver=new ChromeDriver();
      
      driver.get("http://www.qaautomated.com");
 
      Thread.sleep(5000);
  } 
 
  @Test(dataProvider = "search")
  
  public void test(String searchtext) throws Exception {
 
   
      driver.findElement(By.xpath("*//input[@class='search-field']")).sendKeys(searchtext);
      
      driver.findElement(By.xpath("*//input[@class='search-submit']")).click();
 
      
  }
 
  @AfterMethod
 
  public void afterMethod() {
 
    driver.close();
 
  }
 
  @DataProvider
 
  public Object[][] search() throws Exception{
 
     // Setting up the Test Data Excel file
 
   ExcelUtils.setExcelFile("C:\Users\manojjai\Documents\dataprovider.xlsx","Sheet1");
 
   sTestCaseName = this.toString();
 
    // From above method we get long test case name including package and class name etc.
 
    // The below method will refine your test case name, exactly the name use have used
 
    sTestCaseName = ExcelUtils.getTestCaseName(this.toString());
 
     // Fetching the Test Case row number from the Test Data Sheet
 
     // Getting the Test Case name to get the TestCase row from the Test Data Excel sheet
 
   iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,0);
 
     Object[][] testObjArray = ExcelUtils.getTableArray("C:\Users\manojjai\Documents\dataprovider.xlsx","Sheet1",iTestCaseRow);
 
      return (testObjArray);
 
  }
 
}

Понравилась статья? Поделить с друзьями:
  • Data processing with excel
  • Dan peek doer of the word
  • Dallas lock word temp
  • Dale meaning of word
  • Dalatunes lesson plan 9grade excel