如何在页面对象模型设计中使用Selenium ExpectedConditions?
问题描述:
希望我不是第一个遇到此问题的人。如何在页面对象模型设计中使用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定位器灵活地使用显式等待。
非常感谢,
答
我使用页面对象所有的时间,但我在类,而不是元素的顶部有定位器。然后根据需要使用定位器来单击按钮等。这样做的好处是我只需要访问页面上的元素,避免陈旧的元素异常等。请参见下面的简单示例。
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执行任何操作。