javaseleniumselenium-webdriverjxl

Compare values with Selenium and JXL


The following code reads the spreadsheet cell values ​​with the JXL plugin and then compares these values with the values ​​on the page and chooses the matching value from the combo box.

The code I have works but it is case sensitive, the value must be identical. I want to improve this code to search the combo box faster and select the closest value without being identical. Currently it runs through all values slowly.

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.");
}

Solution

  • I put some comments in the code that explains what I'm doing and makes corrections on a few things.

    1. Instead of using an int and setting it to 0/1, use a boolean and set it to true/false.
    2. This loop should be faster because I'm not selecting each option as I loop. You can examine the text of each option without selecting it... then once you find a match, select the match.
    3. Use break to exit a loop instead of setting the counter to max value.

    Give this code a try.

    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.");
    }