如何使用Page Factory通过另一个WebElement查找WebElement

时间:2013-06-21 00:08:02

标签: c# selenium webdriver selenium-webdriver

对源代码进行了简短的扫描,不确定最佳做法是什么。

例如,假设我有一个页面对象'DummyPage',它有两个面板元素TopPanelBottomPanel。每个面板都有一些元素,可以通过TopPanel.FindElement()代替driver.FindElement()找到。如何申请Page Factory?

我知道PageFactory.InitElements(ISearchContext, Object)接收ISearchContext,但是,我不知道如何将它用于一个类中的页面和面板元素。

public class DummyPage {

    private IWebDriver driver;

    public DummyPage(IWebDriver driver) {
        this.driver = driver;
    }

    public IList<IWebElement> DummyLinks {
        get { return driver.FindElements(By.CssSelector(".some-dummy-links")); }
    }

    public IWebElement TopPanel {
        get { return driver.FindElement(By.Id("top-panel")); }
    }

    public IWebElement BottomPanel {
        get { return driver.FindElement(By.Id("bottom-panel")); }
    }

    public IWebElement FooInTopPanel {
        get { return TopPanel.FindElement(By.CssSelector(".something")); }
    }

    public IWebElement FooInBottomPanel {
        get { return BottomPanel.FindElement(By.CssSelector(".something")); }
    }
}

public class DummyPageWithPageFactory {

    public DummyPageWithPageFactory(IWebDriver driver) {
        PageFactory.InitElements(driver, this);
    }

    [FindsBy(How = How.CssSelector, Using = ".some-dummy-links")]
    public IList<IWebElement> DummyLinks { get; private set; }

    [FindsBy(How = How.Id, Using = "top-panel")]
    public IWebElement TopPanel { get; private set; }

    [FindsBy(How = How.Id, Using = "bottom-panel")]
    public IWebElement BottomPanel { get; private set; }

    //public IWebElement FooInTopPanel { get; private set; }
    //public IWebElement FooInBottomPanel { get; private set; }
}

如果我对所有实例使用driver.FindElement()并连接所有定位器,我可能会遇到另一种情况,即所有定位器都太长而且我不能在C#属性中使用变量。

[FindsBy(How = How.CssSelector, Using = "#top-panel .blah .blah .super-long-blah .something")]
[FindsBy(How = How.CssSelector, Using = "#top-panel .blah .blah .super-long-blah .something-new")]
[FindsBy(How = How.CssSelector, Using = "#bottom-panel .blah .blah .super-long-blah .something")]

1 个答案:

答案 0 :(得分:1)

请参阅此example

[FindsBy(How = How.Name, Using = "anElementName", Priority = 0)]
[FindsBy(How = How.Name, Using = "differentElementName", Priority = 1)]
public IWebElement thisElement;