Fluent APIの使用を検討する

マーチン・ファウラーは“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("cheese").clickSearchButton();

この流暢な動作を持つGoogleページオブジェクトクラスは次のようになります。

abstract class BasePage {
  protected WebDriver driver;

  public BasePage(WebDriver driver) {
    this.driver = driver;
  }
}

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();
  }
}