[英]Unable to call function from another java class
我正在開發一些硒代碼,並嘗試使用apache POI從Excel工作表中獲取輸入。 到目前為止,我已經設法獲得了輸入,但是我無法在課堂之間轉移輸入。 請參見下面的代碼:
要調用的函數:
package Excel;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Read {
XSSFSheet Names;
public void read() throws Exception{
File src = new File("C:\\Users\\dindo\\Documents\\tests\\d2c-lv-int-01_DATA.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
Names = wb.getSheetAt(0);
}
public void getcell(int row, int col){
String stringresult = Names.getRow(row).getCell(col).getStringCellValue();
String intresult = Names.getRow(row).getCell(col).getStringCellValue();
}
嘗試調用函數:
package Pages;
import Excel.Read;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class DetailsPage {
Read cel = new Read();
cel.getcell(2,4)
@FindBy(how = How.XPATH, using = "/*xpath*/")
public WebElement coveramountelement;
public String coveramount = cel.intresult;
public void EnterDetails() {
coveramountelement.sendKeys(coveramount);
}
}
第10行的所有錯誤都針對cel.getcell(2,4);
我建議像這樣重組您的代碼
函數應被重用-因此將特定變量硬編碼到它們中不是一個好主意。 而且您不存儲任何狀態,因此只需返回所需的對象
public class Read {
public static XSSFSheet getSheet(String file, int sheetIndex) throws Exception{
File src = new File(f);
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
return wb.getSheetAt(sheetIndex);
}
public static Cell getCell(XSSFSheet s, int row, int col) {
return s.getRow(row).getCell(col);
}
現在,使用這些通用函數來完成您的特定任務
public class DetailsPage {
private XSSFSheet names;
public DetailsPage() {
try {
names = Read.getSheet("C:\\Users\\dindo\\Documents\\tests\\d2c-lv-int-01_DATA.xlsx", 0);
} catch (Exception e) {
e.printStackTrace();
}
}
@FindBy(how = How.XPATH, using = "/*xpath*/")
public WebElement coverAmountElement;
public void enterDetails() {
if (names != null) {
XSSFCell c = Read.getCell(names, 2,4);
String coveramount = c.getStringCellValue();
coverAmountElement.sendKeys(coveramount);
}
}
}
除非要初始化變量,否則您不能在其他方法/函數之外調用方法/函數。 此外, getCell
方法返回一個void
,這意味着您不能使用它來分配任何內容。此外,您還缺少分號。 所以改變這個
Read cel = new Read();
cel.getcell(2,4)
對於這樣的事情:
package Pages;
import Excel.Read;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class DetailsPage {
@FindBy(how = How.XPATH, using = "/*xpath*/")
public WebElement coveramountelement;
public void EnterDetails() {
Read cel = new Read();
String coveramount = cel.getcell(2,4);
coveramountelement.sendKeys(coveramount);
}
}
對於getCell
,它是這樣的:
public String getcell(int row, int col){
String stringresult = Names.getRow(row).getCell(col).getStringCellValue();
return stringresult;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.