[英]How to use an instance of a class in an another class in selenium
Login.java
public class Login_Details {
public static WebDriver dr;
public void verifyLogin() throws Exception {
dr= new FirefoxDriver();
dr.get("http://www.nexterp.in:9992/NextERPQA/nerp/login");
FileInputStream fi= new FileInputStream("C:\\NexterpProject\\Next_Testdata\\src\\Testdata.xls");
Workbook wb= Workbook.getWorkbook(fi);
Sheet s= wb.getSheet(0);
dr.findElement(By.id("userName")).sendKeys(s.getCell(0,1).getContents());
dr.findElement(By.id("password")).sendKeys(s.getCell(1,1).getContents());
dr.findElement(By.xpath(".//*[@id='loginForm']/a")).click();
Thread.sleep(3000);
System.out.println("Thank you for Logging in");
}
和Logout.java
public class Logout{
public static WebDriver dr;
public void comesOut() throws Exception{
Thread.sleep(1000);
dr.findElement(By.xpath("html/body/div[1]/div/div/div/div[2]/div/a[2]")).click();
System.out.println("Thank you for clicking on Logout");
dr.quit();
}
}
在以上兩個程序中,為webdriver dr創建了一個實例; 我的問題是,不是每次都為新類創建新實例,而是告訴我如何在程序中使用該dr ?
您可以將靜態對象的初始化從方法移動到變量聲明,例如
public static WebDriver dr = new FirefoxDriver();
然后在任何地方重復使用
Login_Details.dr
使驅動程序處於初始化階段。
public static WebDriver dr = new FirefoxDriver();
您可以像下面那樣在“ Logout.java”中擴展“ Login.java”類 (也可以在Logout類中導入Login類 ):
public class Logout extends Login
然后,您可以在“ Logout.java”中直接使用dr
創建一個包含驅動程序初始化且驅動程序為靜態的BaseClass。 將BaseClass擴展到每個類並重用驅動程序對象。
public class BaseClass{
static WebDriver driver;
.
.
.
}
在Login_Details中
public class Login_Details extends BaseClass{
public void verifyLogin() throws Exception {
driver= new FirefoxDriver();
driver.get("http://www.nexterp.in:9992/NextERPQA/nerp/login");
<your code>
}
}
並在Logout.java中
public class Logout extends BaseClass{
public void comesOut() throws Exception{
driver.findElement(By.xpath("html/body...")).click();
<your code>
}
}
而且,如果您不想使驅動程序成為靜態,則最好遵循PageObject設計模式。 使用它,您可以提供您的代碼而無需擴展BaseClass。
在Login_Details中
public class Login_Details{
WebDriver driver = null;
public Logout verifyLogin() throws Exception {
driver= new FirefoxDriver();
driver.get("http://www.nexterp.in:9992/NextERPQA/nerp/login");
<your code>
return new Logout(driver);
}
}
並在Logout.java中
public class Logout{
WebDriver driver;
public Logout(WebDriver driver) {
this.driver = driver;
}
public void comesOut() throws Exception{
driver.findElement(By.xpath("html/body...")).click();
<your code>
}
}
因此,您的測試方法如下所示:
@Test
public void test1() {
Login login = new Login();
Logout logout = login.doLogin();
logout.doLogout();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.