JUnit/TestNGによるSeleniumのガイド

JUnit / TestNGを使用したSeleniumのガイド

1. 前書き

この記事は、Seleniumを操作し、JUnitTestNGを使用してテストを作成するための簡単で実用的な紹介です。

2. セレンの統合

このセクションでは、簡単なシナリオから始めます。ブラウザウィンドウを開き、特定のURLに移動して、ページ上の目的のコンテンツを探します。

2.1. Mavenの依存関係

pom.xmlファイルに、次の依存関係を追加します。


    org.seleniumhq.selenium
    selenium-java
    3.4.0

最新バージョンはMaven Central Repositoryにあります。

2.2. セレン構成

まず、SeleniumConfigという名前の新しいJavaクラスファイルを作成します。

public class SeleniumConfig {

    private WebDriver driver;

    //...

}

Selenium 3.xバージョンを使用している場合、webdriver.gecko.driverというシステムプロパティを使用して、実行可能GeckoDriverファイル(OSに基づく)のパスを指定する必要があります。GeckoDriverの最新バージョンはGithub Geckodriver Releasesからダウンロードされます。

コンストラクターでWebDriverを初期化します。また、ページ上の要素が表示されるのを待つWebDriverのタイムアウトとして5秒を設定します。

public SeleniumConfig() {
    Capabilities capabilities = DesiredCapabilities.firefox();
    driver = new FirefoxDriver(capabilities);
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}

static {
    System.setProperty("webdriver.gecko.driver", findFile("geckodriver.mac"));
}

static private String findFile(String filename) {
   String paths[] = {"", "bin/", "target/classes"};
   for (String path : paths) {
      if (new File(path + filename).exists())
          return path + filename;
   }
   return "";
}

この構成クラスには、当面は無視するいくつかのメソッドが含まれていますが、このシリーズの第2部でこれらについて詳しく説明します。

次に、SeleniumExampleクラスを実装する必要があります。

public class SeleniumExample {

    private SeleniumConfig config;
    private String url = "http://www.example.com/";

    public SeleniumExample() {
        config = new SeleniumConfig();
        config.getDriver().get(url);
    }

    // ...
}

ここでは、SeleniumConfigを初期化し、移動先のURLを設定します。 同様に、ブラウザを閉じてページのタイトルを取得するための簡単なAPIを実装します。

public void closeWindow() {
    this.config.getDriver().close();
}

public String getTitle() {
    return this.config.getDriver().getTitle();
}

example.comのAboutセクションに移動するには、ホームページの読み込み時にオーバーレイをチェックして閉じるcloseOverlay()メソッドを作成する必要があります。 その後、getAboutexamplePage()メソッドを使用して[バージョン情報]ページに移動します。

public void getAboutexamplePage() {
    closeOverlay();
    clickAboutLink();
    clickAboutUsLink();
}

private void closeOverlay() {
    List webElementList = this.config.getDriver()
      .findElements(By.tagName("a"));
    if (webElementList != null) {
       webElementList.stream()
         .filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title")))
         .filter(WebElement::isDisplayed)
         .findAny()
         .ifPresent(WebElement::click);
    }
}

private void clickAboutLink() {
    this.config.getDriver().findElement(By.partialLinkText("About")).click();
}

private void clickAboutUsLink() {
    Actions builder = new Actions(config.getDriver());
    WebElement element = this.config.getDriver()
      .findElement(By.partialLinkText("About example."));
    builder.moveToElement(element)
      .build()
      .perform();
}

表示されたページで必要な情報が利用可能かどうかを確認できます。

public boolean isAuthorInformationAvailable() {
    return this.config.getDriver()
      .findElement(By.cssSelector("article > .row > div"))
      .isDisplayed();
}

次に、このクラスをJUnitとTestNGの両方でテストします。

3. JUnitを使用

SeleniumWithJUnitLiveTest:として新しいテストクラスを作成しましょう

public class SeleniumWithJUnitLiveTest {

    private static SeleniumExample seleniumExample;
    private String expectedTitle = "example | Java, Spring and Web Development tutorials";

    // more code goes here...

}

org.junit.BeforeClass@BeforeClassアノテーションを使用して、初期設定を行います。 このsetUp()メソッドでは、SeleniumExampleオブジェクトを初期化します。

@BeforeClass
public static void setUp() {
    seleniumExample = new SeleniumExample();
}

同様に、テストケースが終了したら、新しく開いたブラウザーを閉じる必要があります。 テストケースの実行が終了したときに設定をクリーンアップするために、@AfterClassアノテーションを使用してこれを行います。

@AfterClass
public static void tearDown() {
    seleniumExample.closeWindow();
}

SeleniumExampleメンバー変数のstatic修飾子に注意してください–setUp()およびtearDown()静的メソッドでこの変数を使用する必要があるため–@BeforeClassおよび@AfterClassは静的メソッドでのみ呼び出すことができます。

最後に、完全なテストを作成できます。

@Test
public void whenAboutexampleIsLoaded_thenAboutEugenIsMentionedOnPage() {
    seleniumExample.getAboutexamplePage();
    String actualTitle = seleniumExample.getTitle();

    assertNotNull(actualTitle);
    assertEquals(expectedTitle, actualTitle);
    assertTrue(seleniumExample.isAuthorInformationAvailable());
}

このテストメソッドは、Webページのタイトルがnullではなく、期待どおりに設定されていることを表明します。 それに加えて、ページに期待される情報が含まれていることを確認します。

テストを実行すると、FirefoxでURLが開かれ、Webページのタイトルとコンテンツが確認された後に閉じられます。

4. TestNGを使用

TestNGを使用してテストケース/スイートを実行してみましょう。

Eclipseを使用している場合は、TestNGプラグインがEclipse Marketplaceからダウンロードおよびインストールされる可能性があることに注意してください。

まず、新しいテストクラスを作成しましょう。

public class SeleniumWithTestNGLiveTest {

    private SeleniumExample seleniumExample;
    private String expectedTitle = "example | Java, Spring and Web Development tutorials";

    // more code goes here...

}

org.testng.annotations.BeforeSuiteからの@BeforeSuiteアノテーションを使用して、SeleniumExample classをインスタンス化します。 setUp()メソッドは、テストスイートがアクティブ化される直前に起動されます。

@BeforeSuite
public void setUp() {
    seleniumExample = new SeleniumExample();
}

同様に、org.testng.annotations.AfterSuite@AfterSuiteアノテーションを使用して、テストスイートが完了したら、開いているブラウザを閉じます。

@AfterSuite
public void tearDown() {
    seleniumExample.closeWindow();
}

最後に、テストを実装しましょう。

@Test
public void whenAboutexampleIsLoaded_thenAboutEugenIsMentionedOnPage() {
    seleniumExample.getAboutexamplePage();
    String actualTitle = seleniumExample.getTitle();

    assertNotNull(actualTitle);
    assertEquals(expectedTitle, actualTitle);
    assertTrue(seleniumExample.isAuthorInformationAvailable());
}

テストスイートが正常に完了すると、プロジェクトのtest-outputフォルダーにHTMLレポートとXMLレポートが表示されます。 これらのレポートは、テスト結果をまとめたものです。

5. 結論

この簡単な記事では、JUnitとTestNGの両方を使用してSelenium3テストを作成するための簡単な紹介に焦点を当てました。

いつものように、記事のソースは利用可能ですover at GitHub.