考慮使用流暢的 API
Martin Fowler 創造了 「Fluent API」 一詞。Selenium 已經在其 FluentWait
類別中實作了類似的功能,旨在作為標準 Wait
類別的替代方案。您可以在頁面物件中啟用 Fluent API 設計模式,然後使用如下程式碼片段查詢 Google 搜尋頁面
driver.get( "http://www.google.com/webhp?hl=en&tab=ww" );
GoogleSearchPage gsp = new GoogleSearchPage(driver);
gsp.setSearchString().clickSearchButton();
具有此流暢行為的 Google 頁面物件類別可能如下所示
public abstract class BasePage {
protected WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
}
}
public class GoogleSearchPage extends BasePage {
public GoogleSearchPage(WebDriver driver) {
super(driver);
// Generally do not assert within pages or components.
// Effectively throws an exception if the lambda condition is not met.
new WebDriverWait(driver, Duration.ofSeconds(3)).until(d -> d.findElement(By.id("logo")));
}
public GoogleSearchPage setSearchString(String sstr) {
driver.findElement(By.id("gbqfq")).sendKeys(sstr);
return this;
}
public void clickSearchButton() {
driver.findElement(By.id("gbqfb")).click();
}
}