【问题标题】:How do you use selenium ExpectedConditions in a page object model design?如何在页面对象模型设计中使用 selenium ExpectedConditions?
【发布时间】:2017-04-08 11:21:50
【问题描述】:

希望我不是第一个遇到这个问题的人。

我正在用 C# 编写一些 selenium 测试,在尝试采用页面对象模型设计同时还需要使用 ExpectedConditions 类进行一些显式等待时遇到了两难境地。

假设我将我的元素存储在一个元素映射类中,该类只是一个使用存储在资源文件中的 XPath 调用 .FindElement 方法的属性...

public class PageObject {

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

然后我会继续在各种 selenium 方法中使用该属性。

我遇到的问题是我还需要检查该元素在页面上是否可见,并且在我执行检查之前它会出错(例如,使用 WebDriverWait,将 ExpectedConditions.ElementIsVisible(by) 传递给 .until 方法)。

如何干净地将 IWebElement 和 By 定位器分开,并在需要的地方允许这种显式等待/检查?

TLDR - 如何在维护页面对象模型设计的同时灵活地使用基于元素的 By 定位器的显式等待。

非常感谢,

【问题讨论】:

    标签: c# selenium xpath wait


    【解决方案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(页面对象类)执行任何操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多