Fluent 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();
この Fluent な振る舞いを持つ 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();
}
}