画面操作を伴う自動テストのコツを思い出しやすくするためメモしておく
AIがすぐに作ってくれなかったのでやり方のコツをメモしておく
pom.xmlに以下の依存関係を追加する:
selenium-java junit-jupiter webdrivermanager
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
<scope>test</scope>
</dependency>
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) - ランダムポートでSpringBootアプリケーションを起動 @TestPropertySource - テスト用のプロパティを設定
@LocalServerPort - SpringBootが割り当てたポート番号を取得 WebDriver - Seleniumのブラウザ操作用インスタンス WebDriverWait - 要素の待機処理用
画面操作をカプセル化するためのパターン
- 各画面の操作をクラスとして分離 - テストコードの可読性と保守性が向上
|| public class ReceptionSearchPage? {
private WebDriver driver; private WebDriverWait wait;
public ReceptionSearchPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public ReceptionDetailPage searchAndOpenReceptionDetail(String receptionNo) {
// 画面操作のロジック
return new ReceptionDetailPage(driver, wait);
}
} ||<
@BeforeEach内で実施 - WebDriverManagerでブラウザドライバセットアップ - ブラウザウィンドウの最大化 - ログイン処理
@AfterEach内で実施 - ブラウザの終了(driver.quit())
WebDriverWait?を使用して要素の表示を待機
|| wait.until(ExpectedConditions?.presenceOfElementLocated?(By.cssSelector(".selector"))); ||<
テストの実行制御
||
plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludedGroups>selenium</excludedGroups>
</configuration>
/plugin> ||<
- テストの実行時間が長くなりがち - 環境依存の問題が発生しやすい - CIでの実行時はヘッドレスモードの検討 - 要素の待機時間は適切に設定