我正在使用带有Selenium Web驱动程序的PageObjects模式,例如
public class CategoryPage
{
private IWebDriver driver;
[FindsBy(How = How.CssSelector, Using = ".notFound")]
private IWebElement products;
public CategoryPage(IWebDriver webDriver)
{
driver = webDriver;
}
public bool IsProductList
{
get
{
return products != null; // always true.
}
}
// other stuff
}
我通过以下方式填充:
var page = new CategoryPage(driver);
PageFactory.InitElements(driver, page);
return page;
在查看页面时,即使我将选择器设置为不在页面上的类或css路径,我所拥有的IsProductList
检查也始终返回true。
我应该如何检查存在?
答案 0 :(得分:1)
要确定元素是否存在,您可以使用IList<IWebElement>
声明页面对象,并.Count
知道是否至少有一个元素:
public class CategoryPage {
private IWebDriver driver;
[FindsBy(How = How.CssSelector, Using = ".notFound")]
private IList<IWebElement> products;
public CategoryPage(IWebDriver webDriver) {
driver = webDriver;
}
public bool IsProductList {
get {
return products.Count > 0;
}
}
// other stuff
}
另一种方法是捕捉NoSuchElementException
:
public class CategoryPage {
private IWebDriver driver;
[FindsBy(How = How.CssSelector, Using = ".notFound")]
private IWebElement products;
public CategoryPage(IWebDriver webDriver) {
driver = webDriver;
}
public bool IsProductList {
get {
try {
return products.Equals(products);
} catch (NoSuchElementException) {
return false;
}
}
}
// other stuff
}