Web系開発メモ

Java, C#, HTML, CSS, JavaScript のことなどを書いてます。

Java FluentLeniumでブラウザのテストを自動化する方法

FluentLenium を使って、ブラウザのテストを自動化する方法を書いていきます。

※ FluentLenium は Selenium を使用しています。

バージョン

動作確認で使用した製品のバージョンは以下の通りです。

1. ビルドファイルの作成

Maven のビルドファイルを作成して、ライブラリの依存関係を追加します。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>test-fluentlenium</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.fluentlenium</groupId>
      <artifactId>fluentlenium-assertj</artifactId>
      <version>5.0.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.fluentlenium</groupId>
      <artifactId>fluentlenium-junit-jupiter</artifactId>
      <version>5.0.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-firefox-driver</artifactId>
      <version>4.8.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M8</version>
      </plugin>
    </plugins>
  </build>
</project>

2. テストケースの作成

以下のテストクラスを作成します。

src/test/java/org/example/DuckDuckGoTest.java

package org.example;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.fluentlenium.adapter.junit.jupiter.FluentTest;
import org.junit.jupiter.api.Test;

class DuckDuckGoTest extends FluentTest {
  @Test
  void titleOfDuckDuckGoShouldContainSearchQueryName() {
    // DuckDuckGoのページに移動
    goTo("https://duckduckgo.com");
    // 検索欄に入力
    $("#search_form_input_homepage").fill().with("FluentLenium");
    // サブミット
    $("#search_button_homepage").submit();
    // サブミットしたフォームが消えるまで待機
    await().atMost(5, TimeUnit.SECONDS).until(
      el("#search_form_homepage")
    ).not().present();
    // タイトルに検索文言が含まれていることを確認
    assertThat(window().title()).contains("FluentLenium");
  }
}

3. テストの実行

IDEでテストクラスを実行するか、コマンドラインで以下のコマンドを実行します。

mvn test

テストを実行すると、FireFox が起動して操作が行われます。