簡體   English   中英

我想使用 Fluent wait 返回 void,該怎么做?

[英]I want to return void using Fluent wait, how to do that?

我正在使用 Fluent 等待。 我想返回 void 而不是 Web 元素或 Boolean。我該怎么做? 我試過這樣。 代碼片段如下

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofSeconds(3)).ignoring(NoSuchElementException.class)

    wait.until(new Function<WebDriver, Void>() {
            public void apply(WebDriver driver) {
            if( driver.findElement(By.id("foo")).isDisplayed())
                driver.findElement(By.id("foo")).click();
            }
        });
    }

但是,它在 void 時給我錯誤:

返回類型與 Function<WebDriver,Void>.apply(WebDriver) 不兼容

注意:我只想返回無效。 那可能嗎?

答案是否定的,我想。


我們可以從api 文檔中找到一些有用的信息。

它解釋了這樣的Returns

如果 function 在超時到期前返回與 null 或 false 不同的內容,則函數的返回值。

所以,function不可能同時正確處理void和null。

我認為您誤解了等待 Function 的用法。一旦滿足條件,它應該返回 Boolean 或 WebElement。 您正試圖在方法內部單擊,這不是它的預期使用方式。

你真的不需要 FluentWait 在這里。 您可以使用 WebDriverWait 來簡化此過程。

new WebDriverWait(driver, 30).until(ExpectedConditions.elementToBeClickable(By.id("foo"))).click();

這將等待最多 30 秒讓元素可點擊,如果沒有超時,返回的元素將被點擊。


對於您的評論......在那種情況下,我會編寫一個單獨的方法ElementExists返回一個WebElement 如果返回的WebElement不是null ,則單擊它。

輔助方法

public static WebElement ElementExists(By locator, int timeout)
{
    try
    {
        return new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOfElementLocated(locator));
    } catch (TimeoutException e)
    {
        return null;
    }
}

腳本代碼

WebElement ele = ElementExists(By.id("foo"), 30);
if (ele != null)
{
    ele.click();
}

您可以使用return this ,它返回當前使用 FluentWait 的 class 的實例,您可以忽略它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM