Search code examples
javaseleniumclasswait

How can i use (WebElement webdriverWait till element is clickable) in method and call that method for re use


As per my code below, i need to use Wait element regularly. Is there any way where as i can re use this code by calling method?

Any help or suggestion would be grateful.

public static By header = By.xpath("//*[@id=\'content\']/h1");

 public static void ClickLink_Accounts() throws IOException {
    WebDriverWait wait = new WebDriverWait(driver, 50);
    WebElement wait2 = wait.until(ExpectedConditions.elementToBeClickable(header));
    find(Accounts).isDisplayed();
    CaptureScreenshot.Screenshot(driver,"Application HomePage-");
}

public static void ClickLink_Tasks() throws IOException {
    WebDriverWait wait = new WebDriverWait(driver, 50);
    WebElement wait2 = wait.until(ExpectedConditions.elementToBeClickable(header));
    find(Tasks).isDisplayed();
    CaptureScreenshot.Screenshot(driver,"Application HomePage-");
}

Solution

  • I think what you are looking for is something like this

    public static void ClickLink_Accounts() throws IOException
    {
        waitForHeader();
        find(Accounts).isDisplayed();
        CaptureScreenshot.Screenshot(driver, "Application HomePage-");
    }
    
    public static void ClickLink_Tasks() throws IOException
    {
        waitForHeader();
        find(Tasks).isDisplayed();
        CaptureScreenshot.Screenshot(driver, "Application HomePage-");
    }
    
    public static void waitForHeader()
    {
        new WebDriverWait(driver, 50).until(ExpectedConditions.elementToBeClickable(header));
    }
    

    But... when I look at your two ClickLink* methods, I see a lot of duplicated code. I would look for a way to combine those two (and maybe other future methods) into one that accepts a parameter. I'm assuming Accounts and Tasks are By locators since you are passing into a method find()? If so, you can do this

    public static void ClickLink(By locator) throws IOException
    {
        waitForHeader();
        find(locator).isDisplayed();
        CaptureScreenshot.Screenshot(driver, "Application HomePage-");
    }
    

    and significantly simplify your code. See DRY for more info.