2017-04-08 81 views
0

希望我不是第一個遇到此問題的人。如何在頁面對象模型設計中使用Selenium ExpectedConditions?

我正在用C#編寫一些硒測試,並且在嘗試adobt頁面對象模型設計時遇到困境,同時還需要使用ExpectedConditions類進行一些顯式等待。

比方說,我存儲我的元素中的一個元素的地圖類,很簡單,就是要求使用存儲在資源文件的XPath的.FindElement方法的屬性...

public class PageObject { 

    public IWebElement Element 
    { 
     get { return DriverContext.Driver.FindElement(By.XPath(Resources.Element)); } 
    } 
} 

然後我會去在各種硒方法中使用該屬性。

我的問題是我也需要檢查這個元素是否在頁面上可見,並且在我執行檢查之前會出錯(例如,使用WebDriverWait,將ExpectedConditions.ElementIsVisible(by)傳遞給.until方法)。

我該如何幹淨地分離出IWebElement和By locator並允許在需要的地方進行顯式等待/檢查?

TLDR - 如何維護頁面對象模型設計,同時還可以根據我的元素的By定位器靈活地使用顯式等待。

非常感謝,

回答

1

我使用頁面對象所有的時間,但我在類,而不是元素的頂部有定位器。然後根據需要使用定位器來單擊按鈕等。這樣做的好處是我只需要訪問頁面上的元素,避免陳舊的元素異常等。請參見下面的簡單示例。

class SamplePage 
{ 
    public IWebDriver Driver; 
    private By waitForLocator = By.Id("sampleId"); 

    // please put the variable declarations in alphabetical order 
    private By sampleElementLocator = By.Id("sampleId"); 

    public SamplePage(IWebDriver webDriver) 
    { 
     this.Driver = webDriver; 

     // wait for page to finish loading 
     new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(waitForLocator)); 

     // see if we're on the right page 
     if (!Driver.Url.Contains("samplePage.jsp")) 
     { 
      throw new InvalidOperationException("This is not the Sample page. Current URL: " + Driver.Url); 
     } 
    } 

    public void ClickSampleElement() 
    { 
     Driver.FindElement(sampleElementLocator).Click(); 
    } 
} 

我會建議不要存儲在定位器一個單獨的文件,因爲它打破了網頁對象模型的咒語這一切都與網頁雲在頁面對象之一。除了一個文件之外,您不必打開任何文件就可以對頁面對象類Page X執行任何操作。

相關問題