2011/03/26

Moving to Selenium 2 on WebDriver, Part No.2

In the following examples the location is always of type org.openqa.selenium.By, while locator is the old Selenium string.

Select a single item in select by label

Selenium 1:
selenium.select(locator,"label=" + optionLabel);

Selenium 2:
Select select = (Select)driver.findElement(location);
select.selectByVisibleText(optionLabel);

Select a single item in select by value

Selenium 1:
selenium.select(location,"value=" + optionValue);

Selenium 2:
select.selectByValue(optionValue);

Write text to an input field

Selenium 1:
selenium.type(locator, text);

Selenium 2:
driver.findElement(location).sendkeys(text);

Get text content of an element

Selenium 1:
selenium.getText(locator);

Selenium 2:
driver.findElement(location).getText();

Setting a checkbox to 'checked' state

Selenium 1:
selenium.check(locator);

Selenium 2:
driver.findElement(location).setSelected();


Javascript in MSIE

When using Javascript (through JavascriptExecutor's executeScript()) you can get unexpected behaviour - MSIE crashes without useful error message when you access some Javascript objects in browser.

To cope with this on Windows 7, check your Protected Mode settings (Tools > Internet Options > Security) and set it to the same value for all zones. I don't know if Windows XP is also affected and how to se it it such case.

Execute Javascript

For all following examples let's define:
JavascriptExecutor js = (JavascriptExecutor) driver;

Selenium 1:
selenium.runScript(script);

Selenium 2:
js.executeScript(script);

Execute Javascript and get result

Selenium 1:
scriptResult = selenium.getEval(scriptReturningString);

Selenium 2:
String scriptResult = (String)js.executeScript(scriptReturningString);

WebDriver requires the script to begin with "return". It's easy to miss it in documentation. Script runs in context of a currently selected window - you do not need any tricks for that as in Selenium 1. Also the result is casted to matching Java type.

No comments:

Post a Comment