[英]how to give wait to driver.get() explicitly in selenium using java
[英]How do I create a driver.get function in Selenium that will be called from another class?
好的,所以我正在使用POM
在Selenium/Maven
創建一種框架。 該項目有三個包
這是我來自Library類的代碼:
package util;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Lib {
//Question is regarding the method below
public static WebElement get(WebDriver driver, String url) {
WebElement link = driver.get(url);
return link;
}
public static WebElement findelement(WebDriver driver, String xpath) {
WebElement e = driver.findElement(By.xpath(xpath));
return e;
}
public static void sleep(WebDriver driver, int sec) throws InterruptedException {
Thread.sleep(sec*1000);
}
}
我希望能夠從測試類的Lib類中調用get方法(第一個)。 這是我的測試類代碼:
package test;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import util.Lib;
public class Test extends Lib{
static WebDriver driver = new ChromeDriver();
@Before
public void before() {
System.out.println("Before Class starts here");
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\TQ\\sel\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
Lib l = new Lib();
l.get(driver, "https://www.google.com/");
}
}
我知道我可以輕松地在測試類中執行driver.get(url)
,但是我想知道為什么它對於lib類中的其他函數不起作用。
這是我得到的錯誤消息, "cannot convert from void to WebElement"
。
提前致謝。
您必須將webdriver的引用對象從測試類傳遞到lib。 從測試類中刪除extends Lib
。 在lib類中創建一個構造函數以初始化參考對象。 Library類應該看起來像這樣。
package util;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Lib {
WebDriver driver;
public Lib(WebDriver driver){
this.driver = driver;
}
//Question is regarding the method below
public static WebElement get(String url) {
WebElement link = driver.get(url);
return link;
}
public static WebElement findelement(String xpath) {
WebElement e = driver.findElement(By.xpath(xpath));
return e;
}
public static void sleep(int sec) throws InterruptedException {
Thread.sleep(sec*1000);
}
}
現在,使用new運算符創建Lib對象時,必須傳遞驅動程序實例 。 構造函數會將驅動程序引用傳遞給本地驅動程序變量,這將允許Test類使用Lib類方法。
Lib l = new Lib(driver);
l.get("https://www.google.com/");
將驅動程序實例傳遞給方法參數的編碼方式將導致空指針異常。
此方法無效。 它應該看起來像:
//Question is regarding the method below
public static void get(WebDriver driver, String url) {
driver.get(url);
}
僅此而已。 在這種情況下,您無需返回任何東西。
錯誤說明了一切:
"cannot convert from void to WebElement"
您已經編寫了方法public static WebElement get(WebDriver driver, String url) {}
。 但是get()不返回任何內容,並定義為:
get(java.lang.String url)
Load a new web page in the current browser window.
Return Type :
void
因此,當您調用WebElement時,link = driver.get(url);。 , return type
與函數調用不匹配,並引發錯誤。
解決的辦法是使退貨為空 。 在driver
打開URL
您可以通過WebDriver
實例(即, driver
輕松地與Web Browser
實例進行交互,如下所示:
public static void get(WebDriver driver, String url) {
driver.get(url);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.