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());
Related
The code in the "basePageNavigation" #Test is running fine on the first data set, but when the method is ran the second time, the first line in it:
driver.get(prop.getProperty("url"));
is ignored, and thus the test fails on the first findElement method called. When I run this in debug mode having a breakpoint at that line, it works fine. Code:
package Academy;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import pageObjects.ForgotPassword;
import pageObjects.Landingpage;
import pageObjects.Loginpage;
import resources.base;
public class Homepage extends base{
public static Logger log = LogManager.getLogger(Homepage.class.getName());
public WebDriver driver;
#BeforeTest
public void initialize() throws IOException
{
driver=initializeDriver();
log.info("Driver initialized");
}
#Test(dataProvider="getData")
public void basePageNavigation(String username, String password, String text) throws IOException
{
driver.get(prop.getProperty("url"));
Landingpage l=new Landingpage(driver);
Loginpage lp = l.getLogin();
lp.getEmail().sendKeys(username);
lp.getPassword().sendKeys(password);
lp.getLoginBtn().click();
ForgotPassword fp = lp.forgotPassword();
fp.getEmail().sendKeys("test");
fp.nextButton().click();
}
#DataProvider
public Object[][] getData()
{
//Row (first value) stands for how many different data types the test will run
//Column (second value) stands for how many values are parsed per test
Object[][] data = new Object[2][3];
// First row
data[0][0] = "nonResabc#qa.com";
data[0][1] = "12345";
data[0][2] = "Non Restricted User";
//Second Row
data[1][0] = "Resabc#qa.com";
data[1][1] = "34567";
data[1][2] = "Restricted User";
return data;
}
#AfterTest
public void tearDown()
{
driver.close();
}
}
I've got an XLSX Excel file with a single cell.
When loaded using POI's WorkbookFactory, it's read correctly as a single cell.
When read using POI's XSSFSheetXMLHandler, it's read as though it was two separate cells.
Sheet XML:
<?xml version="1.0" encoding="UTF-8"?>
<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:sheetData>
<x:row>
<x:c t="inlineStr">
<x:is>
<x:r>
<x:rPr>
<x:rFont val="Segoe UI Emoji"/>
</x:rPr>
<x:t xml:space="preserve">π</x:t>
</x:r>
<x:r>
<x:t xml:space="preserve">more text</x:t>
</x:r>
</x:is>
</x:c>
</x:row>
</x:sheetData>
<x:pageSetup paperSize="9" orientation="portrait" />
</x:worksheet>
Normally you'd expect to see a single item of text per cell, but here it's in two blocks - one formatted using a different font to the other.
Code:
import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Iterator;
import javax.xml.parsers.SAXParserFactory;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class MultiTagTest {
public static void main(final String[] args) throws Exception {
final File file = new File("Minimised.xlsx");
try (OPCPackage xlsxPackage = OPCPackage.open(file, PackageAccess.READ)) {
final XSSFReader reader = new XSSFReader(xlsxPackage);
final Iterator<InputStream> iter = reader.getSheetsData();
try (InputStream stream = iter.next()) {
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
final XMLReader sheetParser = saxParserFactory.newSAXParser().getXMLReader();
sheetParser.setContentHandler(new XSSFSheetXMLHandler(reader.getStylesTable(),
new ReadOnlySharedStringsTable(xlsxPackage), new SheetContentsHandler() {
#Override
public void startRow(final int rowNum) {
}
#Override
public void endRow(final int rowNum) {
}
#Override
public void cell(final String cellReference, final String formattedValue,
final XSSFComment comment) {
System.out.println(MessageFormat.format(
"XSSFSheetXMLHandler Cell - cellReference={0}, formattedValue={1}, comment={2}",
cellReference, formattedValue, comment));
}
}, true));
sheetParser.parse(new InputSource(stream));
}
}
try (Workbook workbook = WorkbookFactory.create(file, null, true)) {
final Row row = workbook.getSheetAt(0).getRow(0);
for (int col = row.getFirstCellNum(); col < row.getLastCellNum(); col++) {
System.out.println(MessageFormat.format("WorkbookFactory Cell - {0}", row.getCell(col)));
}
}
}
}
Output:
XSSFSheetXMLHandler Cell - cellReference=null, formattedValue=π, comment=null
XSSFSheetXMLHandler Cell - cellReference=null, formattedValue=more text, comment=null
WorkbookFactory Cell - πmore text
From inside the SheetContentsHandler's cell method, it's not possible to tell that they were the same cell.
Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.
Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx
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
hello:
I'm writing code in java for nutch(open source search engine) to remove the movments from arabic words in the indexer.
I don't know what is the error in it.
Tthis is the code:
package com.mycompany.nutch.indexing;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.getData().parse.getData();
public class InvalidUrlIndexFilter implements IndexingFilter {
private static final Logger LOGGER =
Logger.getLogger(InvalidUrlIndexFilter.class);
private Configuration conf;
public void addIndexBackendOptions(Configuration conf) {
// NOOP
return;
}
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
if (url == null) {
return null;
}
char[] parse.getData() = input.trim().toCharArray();
for(int p=0;p<parse.getData().length;p++)
if(!(parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω' ||parse.getData()[p]=='Ω'||parse.getData()[p]=='Ω' ||parse.getData()[p]=='"' ))
new String.append(parse.getData()[p]);
return doc;
}
public Configuration getConf() {
return conf;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
}
I think that the error is in using parse.getdata() but I don't know what I should use instead of it?
The line
char[] parse.getData() = input.trim().toCharArray();
will give you a compile error because the left hand side is not a variable. Please replace parse.getData() by a unique variable name (e.g. parsedData) in this line and the following lines.
Second the import of
import org.apache.nutch.parse.getData().parse.getData();
will also fail. Looks a lot like a text replace issue.