检查是否有IWebElement的所有脑干使用硒PageObjects时 [英] Check for existance of an IWebElement when using PageObjects with Selenium
问题描述
我使用PageObjects模式与硒的网络驱动器,如:
公共类CategoryPage
{
私人IWebDriver驱动程序;
[FindsBy(如何= How.CssSelector,使用=.notFound)]
私人IWebElement产品;
公共CategoryPage(IWebDriver的webdriver)
{
驱动= webdriver的;
}
公共BOOL IsProductList
{
得到
{
回报的产品!= NULL; //总是如此。
}
}
//其他的东西
}
我是通过填充它:
VAR页=新CategoryPage(驱动器);
PageFactory.InitElements(驱动程序,页);
返回页面;
在看一个页面的 IsProductList
检查我也总是返回true,甚至当我选择设置为一个类或CSS路径,是不是在页面上。
我应该如何来检查是否存在?
要确定一个元素存在,你可以使用的IList< IWebElement>
申报页面对象和 .Count之间
来知道是否有至少一个元素:
<预类= 郎咸平-C#prettyprint-覆盖>
公共类CategoryPage {
私人IWebDriver驱动程序;
[FindsBy(如何= How.CssSelector,使用=.notFound)]
私人的IList< IWebElement>产品;
公共CategoryPage(IWebDriver的webdriver){
驱动= webdriver的;
}
公共BOOL IsProductList {
获得{
返回products.Count> 0;
}
}
//其他的东西
}
另一种方法是赶上 NoSuchElementException异常
:
<预类=郎-C#prettyprint-覆盖>
公共类CategoryPage {
私人IWebDriver驱动程序;
[FindsBy(如何= How.CssSelector,使用=.notFound)]
私人IWebElement产品;
公共CategoryPage(IWebDriver的webdriver){
驱动= webdriver的;
}
公共BOOL IsProductList {
获得{
尝试{
返回products.Equals(产品);
}赶上(NoSuchElementException异常){
返回FALSE;
}
}
}
//其他的东西
}
I am using PageObjects pattern with Selenium web driver, e.g.
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
}
I am populating it via:
var page = new CategoryPage(driver);
PageFactory.InitElements(driver, page);
return page;
When looking at a page the IsProductList
check I have is always returning true, even when I set the selector to a class or css path that isn't on the page.
How should I be checking for existence?
To determine if an element is present, you can use IList<IWebElement>
to declare the page object and .Count
to know if there is at least one element:
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
}
Another way would be to catch the 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
}
这篇关于检查是否有IWebElement的所有脑干使用硒PageObjects时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!