2011/03/15

Moving to Selenium 2 on WebDriver, Part No.1

I am in the process of trying to move code of some test to the Selenium 2 WebDriver. This is the first part of series of short articles about how to "translate" old Selenium API to the WebDriver-based one.

In following, let's state that xpathLocator is Selenium 1 locator, while xpathFinder is more or less By.xpath(xpathLocator),selenium is instance of Selenium, driver is instance of WebDriver (FirefoxDriver).

Is an element present on a page ?

Selenium 1:
selenium.isElementPresent(xpathLocator);

Selenium 2:
driver.findElements(xpathFinder).size()>0;

Get HTML source of a page

Selenium 1:
selenium.getHtmlSource();

Selenium 2:
driver.getPageSource();

Is a text present on a page ?

Selenium 1:
selenium.isTextPresent(text);

Selenium 2:
driver.getPageSource().contains(text);

Go to relative URL
The relativeUrl is URL relative to initial URL, i.e. without the "http://hostname".

Selenium 1:
selenium.open(relativeUrl);

Selenium 2:
driver.get( initialUrl + relativeUrl );

This call is blocking, i.e. further processing is stopped until the page is loaded.

To open an URL relative to the currently used  one, use  driver.getCurrentUrl():
driver.get( driver.getCurrentUrl() + relativeUrl );

Is an element visible on a page?

Selenium 1:
selenium.isVisible(location)

Selenium 2:
driver.findElement(location) instanceof RenderedWebElement
((RenderedWebElement)driver.findElement(location)).isDisplayed()