6. PageObjectパターンによる型安全なテストケース
最後に、PageObjectパターンの利点をもう一つ実感するために、サンプルアプリケーションに対して「はじめてログインしたユーザーはパスワード変更画面に遷移させたい」という仕様変更が発生したとしましょう。
-
パスワード変更画面
- タイトルは「Password」
- 古いパスワードと新しいパスワード、確認用の新しいパスワードを入力してパスワードを変更する
- パスワード変更に失敗するとパスワード変更画面に遷移する
- パスワード変更に成功するとホーム画面に遷移する
仕様変更対応後のアプリケーションはこちらにデプロイしてあります。
6.1. PasswordPage
新しく追加されたパスワード変更画面を表すPasswordPageクラスは、下記のとおりです。
package com.example.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class PasswordPage {
private final WebDriver driver;
@FindBy(name = "oldpassword")
@CacheLookup
private WebElement oldpassword;
@FindBy(name = "newpassword1")
@CacheLookup
private WebElement newpassword1;
@FindBy(name = "newpassword2")
@CacheLookup
private WebElement newpassword2;
@FindBy(xpath = "//button[@type='submit']")
@CacheLookup
private WebElement updateButton;
public PasswordPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public PasswordPage typeOldPassword(String key) {
oldpassword.sendKeys(key);
return this;
}
public PasswordPage typeNewPassword1(String key) {
newpassword1.sendKeys(key);
return this;
}
public PasswordPage typeNewPassword2(String key) {
newpassword2.sendKeys(key);
return this;
}
public HomePage submitUpdateExpectingSuccess() {
updateButton.click();
return new HomePage(driver);
}
public PasswordPage submitUpdateExpectingFailure() {
updateButton.click();
return new PasswordPage(driver);
}
}
特に難しいところはないと思います。古いパスワードと新しいパスワード、確認用の新しいパスワードを入力するinputフィールドがあり、更新ボタンがあります。
パスワード変更に成功した場合はホーム画面に、失敗した場合はパスワード変更画面に遷移します。


