Search code examples
seleniumselenium-webdriverdatapicker

Find a value inside a datepicker in Selenium WebDriver


I created a method that takes all values from a datepicker and throws it into a variable of type List . Then I made a FOR looking for a specific day and when I find the day, I click on it.

Now I need to implement a routine that displays an error message when the last day is not valid. I am using the JOptionPane.showMessageDialog class to display the error. But the problem is that the message appears every time the script enters the IF to test the value and can not find it.

public void campoRechamada(String dia) {
    driver.findElement(By.id("txtDtRechamada")).click();
    WebElement dateWidget = driver.findElement(rechamada);
    // List<WebElement> linhas = dateWidget.findElements(By.tagName("tr"));
    List<WebElement> colunas = dateWidget.findElements(By.tagName("td"));
    for (WebElement cell : colunas) {
        if (cell.getText().equals(dia)) {
            cell.findElement(By.linkText(dia)).click();
            break;
        } else {

            JOptionPane.showMessageDialog(null, "The date entered in the method is invalid: " + dia, "Erro",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

Passage from the parameter to the method. Method that receives the parameter and validates whether the day is valid or not.

Datepicker


Solution

  • Add a boolean flag outsiet for loop and change it to be true when find the day.

    Then check the flag is true or false after the for loop:

    public void campoRechamada(String dia) {
        driver.findElement(By.id("txtDtRechamada")).click();
        WebElement dateWidget = driver.findElement(rechamada);
        // List<WebElement> linhas = dateWidget.findElements(By.tagName("tr"));
        List<WebElement> colunas = dateWidget.findElements(By.tagName("td"));
    
        boolean find = false;
        for (WebElement cell : colunas) {
            if (cell.getText().equals(dia)) {
                find = true;
                cell.findElement(By.linkText(dia)).click();
                break;
            }
        }
    
        if(find == false) {
            JOptionPane.showMessageDialog(null, "The date entered in the method is invalid: " + dia, "Erro",
                    JOptionPane.ERROR_MESSAGE);
        }
    }