将值与Selenium和JXL进行比较

时间:2015-10-02 15:23:59

标签: java selenium selenium-webdriver jxl

以下代码使用JXL插件读取电子表格单元格值,然后将这些值与页面上的值进行比较,并从组合框中选择匹配值。

我的代码有效,但它区分大小写,值必须相同。 我想改进此代码以更快地搜索组合框并选择最接近的值而不相同。目前,它会缓慢地运行所有值。

String valDesejado = tipopromocao;
String valorComboBox = "";
Select verificaOpt = new Select(driver.findElement(By.name("tipoDePromocaoPromocao")));

int tamanhoBox = verificaOpt.getOptions().size();
int variavelVerificadora1 = 0;
System.out.println("Tamanho: " + tamanhoBox);

for (int i = 0; i < tamanhoBox; i++)
{
    verificaOpt.selectByIndex(i);
    valorComboBox = verificaOpt.getFirstSelectedOption().getText().toString();

    if (valDesejado.equalsIgnoreCase(valorComboBox))
    {
        i = tamanhoBox;
        variavelVerificadora1 = 1;
    }

}
if (variavelVerificadora1 == 0)
{
    System.out.println("ALERTA: The Option + valDesejado + "  no comboBox \"tipoDePromocaoPromocao\" not found.");
}

1 个答案:

答案 0 :(得分:1)

我在代码中添加了一些注释,用于解释我正在做的事情并对一些事情做出更正。

  1. 使用int并将其设置为true / false,而不是使用boolean并将其设置为0/1。
  2. 这个循环应该更快,因为我没有选择每个选项作为循环。您可以检查每个选项的文本而不选择它...然后,一旦找到匹配项,请选择匹配项。
  3. 使用break退出循环,而不是将计数器设置为最大值。
  4. 尝试使用此代码。

    String valDesejado = tipopromocao;
    boolean variavelVerificadora1 = false; // use boolean instead of int set to 0/1
    Select verificaOpt = new Select(driver.findElement(By.name("tipoDePromocaoPromocao")));
    System.out.println("Tamanho: " + verificaOpt.getOptions().size());
    // as this loops, the variable 'option' contains the current loops' OPTION element
    // you don't need to select the option to get its text so this loop should be much faster
    // it selects the OPTION once the correct one is found
    for (WebElement option : verificaOpt.getOptions())
    {
        if (valDesejado.equalsIgnoreCase(option.getText()))
        {
            verificaOpt.selectByVisibleText(option.getText()); // select the OPTION match
            variavelVerificadora1 = true; // set the boolean to true to indicate we found a match
            break; // exits the for loop
        }
    }
    
    if (!variavelVerificadora1) // this is the equivalent of variavelVerificadora1 == false, it's basically saying if not true
    {
        System.out.println("ALERTA: The Option" + valDesejado + " no comboBox \"tipoDePromocaoPromocao\" not found.");
    }