2011-08-03 125 views
14

我們使用selenium WebDriver和JBehave在我們的網絡應用程序上運行「集成」測試。我有一個方法將輸入一個值到表單輸入。Selenium WebDriver選擇組合框項目?

@When("I enter $elementId value $value") 
public void enterElementText(final String elementId, final String value) { 
    final WebElement webElement = webdriver.findElement(By.id(elementId)); 
    webElement.clear(); 
    webElement.sendKeys(value); 
} 

但是當我嘗試使用這個在下拉列表中它(不出所料)選擇一個項目失敗

java.lang.UnsupportedOperationException:您可能只設置 元素的值即輸入元素

如何在組合中選擇一個值?

+0

可能重複(http://stackoverflow.com/問題/ 5805585/webdriver-htmlunitdriver-java-drop-down) –

回答

17

這是如何做到這一點:

@When("I select $elementId value $value") 
public void selectComboValue(final String elementId, final String value) { 
    final Select selectBox = new Select(web.findElement(By.id(elementId))); 
    selectBox.selectByValue(value); 
} 
2

Selenium範例是你應該模擬用戶在現實生活中會做什麼。所以這可能是點擊或導航鍵。

Actions builder = new Actions(driver); 
Action action = builder.click(driver.findElement(By.id(elementId))).build(); 
action.perform(); 

只要你得到一個工作選擇器送入findElement你應該沒有問題的。我發現CSS選擇器是涉及多個元素的更好的選擇。你有樣品頁嗎?

+0

不適用於我,我找不到Actions類。 BTW使用硒2.x.但看到我標記爲重複的其他SO問題。 –

+0

下載最新版本。我認爲它曾經被稱爲ActionBuilder什麼的 –

7

支持包中的硒包含了所有你需要:

using OpenQA.Selenium.Support.UI; 

SelectElement select = new SelectElement(driver.findElement(By.id(elementId))); 
select.SelectByText("Option3"); 
select.Submit(); 

您可以通過的NuGet導入它作爲一個單獨的包:http://nuget.org/packages/Selenium.Support

4

通過使用ext js combobox typeAhead使值在UI中可見。

var theCombo = new Ext.form.ComboBox({ 
... 
id: combo_id, 
typeAhead: true, 
... 
}); 

driver.findElement(By.id("combo_id-inputEl")).clear(); 
driver.findElement(By.id("combo_id-inputEl")).sendKeys("The Value you need"); 
driver.findElement(By.id("combo_id-inputEl")).sendKeys(Keys.ARROW_DOWN); 
driver.findElement(By.id("combo_id-inputEl")).sendKeys(Keys.ENTER); 

如果doesn't工作,這也是值得一試的[webdriver的+ HtmlUnitDriver +的Java +下拉]

driver.findElement(By.id("combo_id-inputEl")).sendKeys("The Value you need"); 
driver.findElement(By.className("x-boundlist-item")).click(); 
+0

也適用於Java:給定一些'WebElement templateInput',你可以做'templateInput.sendKeys(STANDARD_TEXT + Keys.ARROW_DOWN + Keys.ENTER);' – barclay