如何在不重复代码的情况下在五个列表框中选择选项(Web元素列表框)?

时间:2016-03-16 06:08:26

标签: java selenium selenium-webdriver

有5个列表框,我在其中分别选择了1个选项:

WebElement listBox=driver.findElement(By.id("country"));//click on country text box
Select select1=new Select(listBox);
select1.selectByVisibleText("India");//select india

WebElement listBox1=driver.findElement(By.id("state"));//click on state text box
Select select2=new Select(listBox1);
select2.selectByVisibleText("delhi");//select delhi

WebElement listBox2=driver.findElement(By.id("district"));//click on district text box
Select select3=new Select(listBox2);
select3.selectByVisibleText("NCR");//select NCR

WebElement listBox3=driver.findElement(By.id("block"));//click on block 
Select select4=new Select(listBox3);  
select4.selectByVisibleText("Block1");//select Block1

WebElement listBox4=driver.findElement(By.id("village"));//click on village text box
Select select5=new Select(listBox4);        
select5.selectByVisibleText("south");//select south

上面的代码太长了 但我必须通过组合列表框的代码来减少代码长度。

4 个答案:

答案 0 :(得分:0)

创建一个方法来查找下拉列表并选择一个选项

public void chooseFromDropdown(By locator, String text) {
    WebElement listBox = driver.findElement(locator);
    Select select = new Select(listBox);
    select.selectByVisibleText(text);
}

并像这样称呼它

chooseFromDropdown(By.id("country"), "india");
chooseFromDropdown(By.id("state"), "delhi");
// ...

答案 1 :(得分:0)

您可以创建一次元素,如: -

WebElement dropboxelement=driver.findElement(By.id("country"));

Select select1=new Select(dropboxelement);
select1.selectByVisibleText("India");

dropboxelement = driver.findElement(By.id("state"));
select1.selectByVisibleText("delhi");

所以......

试一试

希望它会对你有所帮助:)。

答案 2 :(得分:0)

我建议使用一个框架进行硒测试,如Cucumber或Specflow。当然,它需要一些学习,但比使用Selenium separetly更有效。通过这种方式,您的测试将如下所示:

When user selects items in dropdownbox
| dropdownboxID| selectOption|
| country      | india       |
| state        | delhi       |
| district     | NCR         |
| block        | Block1      |
| village      | south       |

创建表后,在代码中(在本例中为C#)定义以下代码:

[When(@"user selects items in dropdownbox")]
public void UserSelectsItemsInDropdownbox(Table table){
    var parameters = table.CreateSet<Parameters>();

    foreach (var parameter in parameters) {
           var dropdownbox = Driver.FindElement(By.Name(dropdownboxID));
           var selectElement = new SelectElement(dropdownbox);
           selectElement.SelectByText(parameters.selectOption);
    }

}

这样,这就是您需要的唯一代码。您可以通过specflow插入其余数据。在这种情况下,您需要在不同的类中定义参数,我将我的类命名为Parameters.cs

答案 3 :(得分:0)

使用多个参数进行迭代:

String[] items = new String[] {
    "country", "India",
    "state", "delhi",
    "district", "NCR",
    "block", "Block1",
    "village", "south",
};

for (int i = 0; i < items.length; i += 2) {
    String name = items[i];
    String text = items[i + 1];
    WebElement element = driver.findElement(By.name(name));
    new Select(element).selectByVisibleText(text);
}