如何在页面对象模型设计中使用硒预期条件?



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

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

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

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

然后我将继续在各种硒方法中使用这种特性.

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

如何干净地分离出 IWebElement 和 By 定位器,并在需要时允许显式等待/检查?

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

非常感谢,

我一直使用页面对象,但我在类的顶部有定位器而不是元素。然后,我根据需要使用定位器单击按钮等。这样做的好处是我只在需要时访问页面上的元素,从而避免了过时的元素异常等。请参阅下面的简单示例。

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();
}
}

我建议不要将定位器存储在单独的文件中,因为它破坏了页面对象模型的口头禅之一,这与页面对象中的页面有关。除了一个文件之外,您不必打开任何文件即可对页面 X(页面对象类)执行任何操作。

最新更新