2016-03-11 46 views
0

我需要知道一種方法來訪問其他方法或其他類中的方法的變量。我已經將一個註冊頁面的所有定位器放在一個方法elements()中,然後我試圖在同一個類A的主方法中使用標識符e1,並且在其他類B中創建了一個類A的對象引用,然後嘗試相同。它不工作,我需要知道這裏的正確方法。Selenium Java變量訪問

public class test3 { 

    public void elements(){ 

    By e1=By.id("at-i"); 
    By e2=By.xpath("//td/td[2]"); 

    } 

    public static void main (String args[]) 
    { 

    WebDriver driver=new FirefoxDriver(); 
    driver.get("http://testwebsite.com"); 
    WebElement a1=driver.findelement(e1); 

    } 
    } 

    class b{ 

    public static void main (String args[]) { 

     test3 x=new test3(); 

     Webelement a2=x.driver.findelement(e2); 

    } 
} 

回答

0

您無法從其他方法或類中的其他類訪問變量。在方法中定義的變量對於該方法來說是局部的。

如果你想在方法之間共享變量,那麼你需要指定它們作爲類的成員變量(我們也沒有在硒中使用main方法)。

在你的情況下,我建議你瞭解TestNG框架。

0

變量E1和E2的局部範圍僅爲elements()方法。

您必須聲明全局變量才能使用該類訪問它們。

提示:聲明elements()方法以外的變量,但在裏面test3類。

0

看看吧。希望下面的代碼將幫助你。

封裝示例;

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 

public class A { 
    public static WebDriver driver = new FirefoxDriver(); 

    public By elements() { 
     By e2 = By.xpath("//td/td[2]"); 
     return e2; 
    } 

    public static void main(String args[]) { 
     A conA = new A(); 
     driver.get("http://testwebsite.com"); 
     WebElement a1 = driver.findElement(conA.elements()); 
     a1.sendKeys("hello"); 
    } 
} 

class B1 { 
    public static void main(String args[]) { 

     A x = new A(); 

     WebElement b1 = x.driver.findElement(x.elements()); 
    } 
}