2013-08-26 43 views
13

爲什麼我應該使用@FindBy vs WebDriver#findElement()Selenium @FindBy vs driver.findElement()

@FindBy強迫我將我所有的變量移動到一個類的級別(當他們大多數只需要在方法級別)。它似乎只能給我打電話PageFactory.initElements(),它爲我處理懶惰初始化。

我錯過了什麼?

回答

31

粗略地說,@FindBy只是查找元素的一種替代方法(正如您所說的,「常用方法」是driver.findElement())。

雖然這個註釋的好處並不是本身。它更好地用於支持PageObject pattern

在幾句,PageObject模式告訴你創建一個類爲你試圖使用/測試系統的每一頁。

所以,而不必(通常driver.findElement()代碼):

public class TestClass { 
    public void testSearch() { 
     WebDriver driver = new HtmlUnitDriver(); 
     driver.get("http://www.google.com/"); 
     Element searchBox = driver.findElement(By.name("q")); 
     searchBox.sendKeys("stringToSearch"); 
     searchBox.submit(); 
     // some assertions here 
    } 
} 

你會定義一個類的網頁(與@FindBy註解爲元素使用):

public class GooglePage { 
    @FindBy(how = How.NAME, using = "q") 
    private WebElement searchBox; 
    public void searchFor(String text) { 
     searchBox.sendKeys(text); 
     searchBox.submit(); 
    } 
} 

並使用它像:

public class TestClass { 
    public void testSearch() { 
     WebDriver driver = new HtmlUnitDriver(); 
     driver.get("http://www.google.com/"); 
     GooglePage page = PageFactory.initElements(driver, GooglePage.class); 
     page.searchFor("stringToSearch"); 
     // some assertions here 
    } 
} 

現在,我知道這可能看起來詳細在fi rst,但只是給它一下,並考慮有幾個測試案例該頁面。如果searchBox的名稱發生變化怎麼辦? (從name"q"id,比如說query?)

在什麼代碼中會有更多的更改使其重新工作?那個沒有頁面對象(和@FindBy)?如果一個頁面的結構變化很大,那麼在哪個代碼中維護會更容易?

還有一些其他的優點,如像附加註釋:

@FindBy(name = "q") 
@CacheLookup 
private WebElement searchBox; 

@CacheLookup使查找的元素只是發生一次。之後,它將被緩存在變量中,並且可以更快地訪問。

希望這會有所幫助。欲瞭解更多詳情,請務必檢查PageFactoryPageObject pattern

+0

那麼說先生... +1我自己比較喜歡在典型的實例化的PageFactory。簡單得多。 – sircapsalot

+1

+1這樣一個詳細的答案.... – Akbar

+0

PageObject模式似乎非常有幫助!但是,我不能像使用.findElement一樣使用該模式嗎? – pyrrhicVictory

-1
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.FindBy; 
public class CommonPageForStudent { 

    @FindBy(name="usname") 
    private WebElement Studentusername; 
    @FindBy(name="pass") 
    private WebElement Studentpassword; 
    @FindBy(xpath="//button[@type='submit']") 
    private WebElement StudentLetmein; 
    @FindBy(id="logoutLink") 
    private WebElement StudentlogoutLnk; 
    public void loginToStudent(String username , String password){ 
     Studentusername.sendKeys(username); 
     Studentpassword.sendKeys(password); 
     StudentLetmein.click(); 

     } 

    //when you call this methods from another class write this 2 line code that class 
    //CommonPageForStudent page = PageFactory.initElements(driver,  CommonPageForStudent.class); 
    // page.loginToStudent("",""); 

    public void logOut(){ 
     StudentlogoutLnk.click(); 
    } 
    //page.logOut(); method call 

}` 
+1

您能否爲此代碼添加一些解釋? – mlkn

0

我不喜歡@FindBy註釋,因爲然後IntelliJ不再檢測是否正在使用該變量,這使得它很難清理。

相關問題