Search code examples
webdriver

Problem with PageFactory.InitElements in WebDriver API c# .NET


I am trying to create WebDriver UI tests framework using Page Object pattern, using the following URL as a reference: http://www.peternewhook.com/2010/09/automated-testing-pageobjects-webdriver/

As per example I have created 3 classes (see below). The problem is with the line return PageFactory.InitElements(_driver, page); in the Search method of the SearchPage class.

When I try to build I get the following error:

The type 'OpenQA.Selenium.ISearchContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'WebDriver

Fair enough, as I am referencing WebDriver.Common.dll, so I tried removing it and added WebDriver.dll to my References and all of a sudden I get the following when I build:

Cannot implicitly convert type 'void' to 'ConsoleApplication1.ResultsPage'

and it fails on the same line; when I hover over it, it says:

Cannot convert expression type 'void' to 'ConsoleApplication1.ResultsPage'.

I also tried referencing both assemblies and thought I could use different usings but it is a no-go, didn't work.

Why can't PageFactory.InitElements be returned when using WebDriver.dll?

Is there a way around it, or can I achieve the same result by changing the architecture slightly?
Your help is much appreciated. Thanks.

using OpenQA.Selenium;

namespace ConsoleApplication1
{
    public class Page
    {
        public IWebDriver _driver;

        public Page(IWebDriver driver)
        {
            this._driver = driver;
        }
    }
}

using OpenQA.Selenium;

namespace ConsoleApplication1
{
    public class ResultsPage : Page
    {
        public ResultsPage(IWebDriver driver)
            : base(driver)
        {
        }

        private IWebElement count;

        public string GetPagesReturned()
        {
            return count.Text;
        }
    }
}

using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;

namespace ConsoleApplication1
{
    public class SearchPage : Page
    {
        public SearchPage(IWebDriver driver) : base(driver)
        {
        }

        private IWebElement q;
        private IWebElement go;

        public ResultsPage Search(string searchStatement)
        {
            q.SendKeys(searchStatement);
            go.Click();
            ResultsPage page = new ResultsPage(_driver);
            return PageFactory.InitElements(_driver, page);
        }
    }
}

Solution

  • The problem is that PageFactory.InitElements() returns void. Rather, it modifies the page you've passed in. Your code should look something like this:

    public ResultsPage Search(string searchStatement)
    {
        q.SendKeys(searchStatement);
        go.Click();
        ResultsPage page = new ResultsPage(_driver);
        PageFactory.InitElements(_driver, page);
        return page;
    }