Eclipse - Data Driven Framework - Error Shown - java

I have written a data driven framework Java program using below 2 classes. Inthis prgram am trying to log into system by taking login ids from external excel file.
DDF_ExcelClass - library java class to take data from external excel
file and will be called in SnapDealLogin_2
SnapDealLogin_2 - datadrivenframework java program which is failed. In
this class am taking login data from external excel file using
DDF_ExcelClass.
The error message shown are java.lang.RuntimeException: and
java.lang.ArrayIndexOutOfBoundsException: 5
Please note if login ids are given inside the program (not taking from external excel file) then SnapDealLogin_2 works good. failing when try to
take login ids from excel file.
I have tried to identify the cause of fail but could not. please help.
// Data Driver Framework - Excel Class stored as Library to reuse
package datadrivenframework;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.io.FileInputStream;
public class DDF_ExcelClass{
XSSFWorkbook Snap_WB;
XSSFSheet Snap_Sheet;
// NAVIGATING TO THE EXCEL FILE
public DDF_ExcelClass(String Path) throws Exception{
File Snap_Excel = new File(Path);
FileInputStream Snap_Input = new FileInputStream(Snap_Excel);
Snap_WB = new XSSFWorkbook(Snap_Input);
Snap_WB.close();
}
// NAVIGATING TO THE EXCEL SHEET AND GETTING THE CELL VALUE THEN RETURNING THE SAME
public String Snap_ok(int SheetIndex, int Row, int Column){
Snap_Sheet = Snap_WB.getSheetAt(SheetIndex);
String Snap_DataR = Snap_Sheet.getRow(Row).getCell(Column).getStringCellValue();
//System.out.println("THE VALUE IN THE ROW " + Row + " IS " + Snap_DataR);
return Snap_DataR;
}
// FINDING THE TOTAL ROW COUNT IN THE DATA SHEET AND RETURNING THE SAME
public int filerowcount(int SheetID){
int rowcount = Snap_WB.getSheetAt(SheetID).getLastRowNum();
//rowcount = rowcount+1;
return rowcount;
}
}
This is a simple data driver framework program where data is taken from external excel file
package datadrivenframework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import datadrivenframework.DDF_ExcelClass;
public class SnapDealLogin_2 {
#Test(dataProvider = "ABN") // declaring that # Test annotation should get value from dataProvider annotation named "ABN" to proceed further
public void Snap_Login(String UserID) throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\hp\\workspace\\Selenium\\browser\\chromedriver.exe"); // declaring the location of Chromedriver
WebDriver Snap = new ChromeDriver(); // initializing webdriver Snap as ChromeDriver
Snap.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // adding implicit wait
Snap.get("https://www.snapdeal.com/");// entering snapdeal web url
Thread.sleep(3000);// adding sleep
Snap.manage().window().maximize(); // maximizing the browser
Thread.sleep(2000);// adding sleep
Snap.findElement(By.xpath(".//*[#id='sdHeader']/div[4]/div[2]/div/div[3]/div[3]/div/span[1]")).click();// clicking Sign-On button
Snap.findElement(By.xpath("//a [#href='https://www.snapdeal.com/login']")).click(); // Clicking Login button
Snap.switchTo().frame("loginIframe"); // Switching the webdriver control to new frame "Loginframe"
Snap.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);// adding implicit wait
Snap.findElement(By.id("userName")).sendKeys(UserID); // entering User id
Snap.findElement(By.id("checkUser")).click(); //clicking "Continue"button
Snap.quit(); // closing the window
}
#DataProvider(name = "ABN") // adding annotation as DataProvider and naming it as "ABN"
public Object [][] Snap_DP() throws Exception{
DDF_ExcelClass DEC = new DDF_ExcelClass("C:\\Users\\hp\\Desktop\\User_Credentials.xlsx");
int rowcount = DEC.filerowcount(0);
Object[][] xlobject = new Object[rowcount][1];
for(int I = 0; I<=rowcount; I++){
xlobject[I][0] = DEC.Snap_ok(0, I, 0);
}
return xlobject;
}
}

Related

Login Logout with different users whose credentials will come from an Excel file one after another using Selenium

I was trying to build a framework where credentials of various users will come from an excel file.
The user will login to the application and perform some actions and then logout. After that another user will do the same, that is login, perform some actions and logout.
I was able to do only onle time and not multipe time. Please can anyone solve this.
Regards
Below is my code
package testCases;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import utilities.Constants;
import utilities.ExcelUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class WebInteractions {
//creating object of ExcelUtils class
static ExcelUtils excelUtils = new ExcelUtils();
//using the Constants class values for excel file path
static String excelFilePath = Constants.Path_TestData + Constants.File_TestData;
public static void main(String args[]) throws IOException {
//set the Chrome Driver path
System.setProperty("webdriver.chrome.driver", "C:\\Apps\\Eclipse\\Selenium\\chromedriver.exe");
//Creating an object of ChromeDriver
WebDriver driver = new ChromeDriver();
//launching the specified URL
driver.get("https://dev2-merchant-admin.canpaydebit.com/");
//Identify the WebElements for the student registration form
WebElement Username = driver.findElement(By.xpath("//input[#placeholder='Email']"));
WebElement Password = driver.findElement(By.xpath("//input[#placeholder='Password']"));
WebElement Login = driver.findElement(By.xpath("//button[#type='button']"));
//calling the ExcelUtils class method to initialise the workbook and sheet
excelUtils.setExcelFile(excelFilePath, "Sheet1");
//iterate over all the row to print the data present in each cell.
for (int i = 1; i <= excelUtils.getRowCountInSheet(); i++)
{
//Enter the values read from Excel in Username, Password
Username.sendKeys(excelUtils.getCellData(i, 0));
Password.sendKeys(excelUtils.getCellData(i, 1));
//Click on submit button
Login.click();
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
//Clicking on Logout button
driver.findElement(By.xpath("//a[#class='d-block accordion-toggle collapsed']")).click();
driver.findElement(By.xpath("//p[normalize-space()='Logout']")).click();
}
}
}
I tried the above code. I'm expecting that one user logs in, perform some action, then logs out, then another user logs in, perform some actions and then logout, and like these all others users. The email and password will be coming from the Excel file.

Run ms-access function using jacob - Run-time error 3073 Updateable Query - Opened it read-only

I'm attempting to run an Access function through Java using Jacob using Application.Run (https://msdn.microsoft.com/en-us/library/office/ff193559.aspx). I am able to open and close an Access database, but not run a function. I suspect the run call actually does go through but that I have opened the file read-only (maybe? not sure I did) which then causes the Access error: Run-time error 3073: Operation must use an updatable query. The query simply appends two strings onto a test table I created, and that query works by hand, but so far not through Java.
If the error is that I've opened it read-only, how can I open it not read-only? If it's something else, how do I call a function (or a macro, either will work) using Jacob? Or you may know some other Java technique besides using Jacob, I'd take that too.
Minimum example:
Java program
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.LibraryLoader;
import com.jacob.com.Variant;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author evans
*/
public class Test {
public static void main(String[] args) {
// Load library/.dll
try {
String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.18-x64.dll" : "jacob-1.18-x86.dll";
FileInputStream inputStream = new FileInputStream(new File(libFile));
File temporaryDll = File.createTempFile("jacob", ".dll");
try (FileOutputStream outputStream = new FileOutputStream(temporaryDll)) {
byte[] array = new byte[8192];
for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
outputStream.write(array, 0, i);
}
}
System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
LibraryLoader.loadJacobLibrary();
temporaryDll.deleteOnExit();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// Open thread
ComThread.InitSTA(true);
// New application
ActiveXComponent ComBridge = new ActiveXComponent("Access.Application");
// Open database
Dispatch.put(ComBridge, "Visible", new Variant(true));
ComBridge.invoke("OpenCurrentDatabase", new Variant("C:/Users/evans/Documents/Book Business/Building Reports/Book Business.accdb"));
// Run function
ComBridge.invoke("Run", new Variant("Test"));
// Shutdown
ComBridge.invoke("Quit");
ComThread.quitMainSTA();
ComThread.Release();
}
}
Access query:
INSERT INTO tblTest ( Test, Test2 )
SELECT "a" AS Expr1, "B" AS Expr2;

Selenium Webdrier using Java: Exception while reading from Excel

I am using SeleniumWebDriver using Java to automation one of the portal applications. As part of this, I want to read username and password from Excel and written below code. But seeing Exception in thread "main" java.lang.NoClassDefFoundError: org/openxmlformats/schemas/drawingml/x2006/main/ThemeDocument Below is the code
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;
import java.util.Random;
public class BankingFaceLift {
static WebDriver driver = null;
public static void main(String[]args){
driver = new FirefoxDriver();
driver.get("https://obsit.enbduat.com/obweb/common/login.jsf?faces-redirect=true");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try
{
File file = new File("TestData.xlsx");
FileInputStream iFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(iFile);
XSSFSheet sheet = wb.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum();
System.out.println("the no of rows are : " + rowCount);
for (int row=1; row<=rowCount; row++)
{
String Username = sheet.getRow(row).getCell(0).getStringCellValue();
String Password = sheet.getRow(row).getCell(1).getStringCellValue();
driver.findElement(By.id("username")).sendKeys(Username);
driver.findElement(By.id("j_idt49")).sendKeys(Password);
driver.findElement(By.id("submit")).click();
I have imported poi-xxx.jar and poi-ooxml.jar1.
Kindly advice Thanks!
You need to import poi-ooxml-schemas jar as well. You can download the jar from here

Argument type mismatch in JUnit

I'm fairly new to Selenium webdriver and Java, previously I used Selenium IDE. I'm trying to read testdata from an Excel sheet. Which is then written to Eclipse console, which works, and should be used to execute the actual test, which doesn't work. The actual test is not executed because I get an error argument type mismatch. The code looks like this:
package Test_Excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
#RunWith(Parameterized.class)
public class TestWithExcelData {
// Our two parameters
private final int input;
private final int resultExpected;
// Constructor
public TestWithExcelData(int input, int result) {
this.input = input;
this.resultExpected = result;
}
#Parameters
public static Iterable<Object []> data() throws BiffException, IOException
{
String FilePath = "C://Selenium//workspace//testproject//src//testdata//TestData.xls";
FileInputStream fs = new FileInputStream(FilePath);
Object[][] object = new Object[6][2];
Workbook wb = Workbook.getWorkbook(fs);
//locate the excel file in the local machine
Sheet sheet = wb.getSheet("IOResult");
int i=1; //avoid header row
while(!(sheet.getCell(0, i).getContents().equals("end"))) //read data till it reaches the cell whose text is ‘end’
{
object[i-1][0]=sheet.getCell(0, i).getContents();
object[i-1][1]=sheet.getCell(1, i).getContents();
System.out.print(sheet.getCell(0, i).getContents() + "\t");
System.out.print(sheet.getCell(1, i).getContents() + "\t");
System.out.println();
i++;
}
return Arrays.asList(object);
}
#Test
public void testSquareOff(){
Assert.assertEquals(resultExpected, MathUtils.square(input));
}
}
Is there somebody who can point me in the right direction?
Thanks in advance
The method sheet.getCell(column, row).getContents() is returning a String, but your constructor expects int.
You may modify the two lines in the data() method:
object[i-1][0] = Integer.valueOf(sheet.getCell(0, i).getContents());
object[i-1][1] = Integer.valueOf(sheet.getCell(1, i).getContents());

How do I use DataProvider with Apache POI

Please help!. Am newbie with Selenium frameworks, I have a method that accepts 5 parameters for booking a party. It uses TestNG DataProvider to read from excel file. The problem is(as shown below) It uses JXL imports which only supports XLS files (excel 2003 or older). I need help with a similar code that uses Apache POI instead so that it will support XLSX and new versions of excel (2007+). Can someone help me please?
package com.suite1;
import util.TestUtil;
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CreatePartyTest extends TestBase1 {
Workbook wb;
Sheet sh1;
int numrow;
#BeforeTest
public void beforeTest() throws IOException
{
initialize();
if (TestUtil.isSkip("CreatePartyTest"))
{
throw new SkipException("Skipping test, check run mode");
}
dr.get(CONFIG.getProperty("testSiteName"));
getobject("signin_link").click();
getobject("username_Signin_input").sendKeys("alexy.dsouza");
getobject("password_input").sendKeys("testing123");
getobject("submit_button").click();
}
#Test(dataProvider="Partydata")
public void createParty (String Partyname, String Date, String Firstname, String Lastname, String email, String mobile) throws InterruptedException
{
getobject("party_link").click();
getobject("start_party_link").click();
getobject("partyname_input").sendKeys(Partyname);
getobject("partydate_input").sendKeys(Date);
getobject("hostfirstname_input").sendKeys(Firstname);
getobject("hostlastname_input").sendKeys(Lastname);
getobject("hostemail_input").sendKeys(email);
getobject("hostmobile_input").sendKeys(mobile);
getobject("make_reservation").click();
}
//source
#DataProvider(name="Partydata")
public Object[][] TestDataFeed(){
try {
// load workbook: this is where i store my excel
wb=Workbook.getWorkbook(new File("C://Workspace//Max//excelfiles//Partydata.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] Accountdata=new Object[numrow-1][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0,j=1;i<numrow-1;i++){
// Fetch first row Accountname
Accountdata[i][0]=sh1.getCell(0,j).getContents();
// Fetch first row BankName
Accountdata[i][1]=sh1.getCell(1,j).getContents();
// Fetch everything else before an empty column
Accountdata[i][2]=sh1.getCell(2,j).getContents();
Accountdata[i][3]=sh1.getCell(3,j).getContents();
Accountdata[i][4]=sh1.getCell(4,j++).getContents();
}// Return 2d array object so that test script can use the same
return Accountdata;
}
}
I cannot solve your exact query , but you can take reference from my code in which i have used .xlsx workbook only and it is working fine for me.
I am able to read data from excel sheet(.xlsx) .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvidersConcept {
#DataProvider(name="Excelsheet")
public Object[][] readData() throws Exception
{
File f = new File("C:/Users/Vikrant/Documents/MavenTesting.xlsx");
FileInputStream fis = new FileInputStream(f);
XSSFWorkbook workBook = (XSSFWorkbook) WorkbookFactory.create(fis);
XSSFSheet sheet=workBook.getSheet("Sheet1");
Object array[][]=new Object[2][2];
for(int i =0;i<2;i++)
{
for( int j=0;j<2;j++)
{
array[i][j]=sheet.getRow(i).getCell(j).toString();
}
}
return array;
}
#Test(dataProvider="Excelsheet")
public void testData(String Username , String password)
{
System.out.println(Username);
System.out.println("Username tested successfully");
System.out.println(password);
System.out.println("password tested successfully");
}
}
enter code here

Categories