JUnit/TestNGを使用したSeleniumのガイド
1. 序章
この記事は、 Selenium を操作し、JUnitとTestNGを使用してテストを作成するための簡単で実用的な紹介です。
2. Seleniumの統合
このセクションでは、簡単なシナリオから始めます。ブラウザウィンドウを開き、特定のURLに移動して、ページ上の目的のコンテンツを探します。
2.1. Mavenの依存関係
pom.xml ファイルに、次の依存関係を追加します。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
最新バージョンは、 Maven CentralRepositoryにあります。
2.2. セレン構成
まず、SeleniumConfigという名前の新しいJavaクラスファイルを作成します。
public class SeleniumConfig {
private WebDriver driver;
//...
}
Selenium 3.xバージョンを使用している場合、 webdriver.gecko.driver というシステムプロパティを使用して、実行可能 GeckoDriver ファイル(OSに基づく)のパスを指定する必要があります。 ] GeckoDriverの最新バージョンは、 Github GeckodriverReleasesからダウンロードできます。
コンストラクターで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.baeldung.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();
}
baeldung.comのAboutセクションに移動するには、ホームページの読み込み時にオーバーレイをチェックして閉じる closeOverlay()メソッドを作成する必要があります。 その後、 getAboutBaeldungPage()メソッドを使用して、AboutBaeldungページに移動します。
public void getAboutBaeldungPage() {
closeOverlay();
clickAboutLink();
clickAboutUsLink();
}
private void closeOverlay() {
List<WebElement> 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() {
Actions actions = new Actions(config.getDriver());
WebElement aboutElement = this.config.getDriver()
.findElement(By.id("menu-item-6138"));
actions.moveToElement(aboutElement).perform();
}
private void clickAboutUsLink() {
WebElement element = this.config.getDriver()
.findElement(By.partialLinkText("About Baeldung."));
element.click();
}
表示されたページで必要な情報が利用可能かどうかを確認できます。
public boolean isAuthorInformationAvailable() {
return this.config.getDriver()
.getPageSource()
.contains("Hey ! I'm Eugen");
}
次に、このクラスをJUnitとTestNGの両方でテストします。
3. JUnitを使用
SeleniumWithJUnitLiveTest:として新しいテストクラスを作成しましょう
public class SeleniumWithJUnitLiveTest {
private static SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
// 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 whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
このテストメソッドは、Webページのタイトルが null ではなく、期待どおりに設定されていることを確認します。 その上、ページに期待される情報が含まれていることを確認します。
テストを実行すると、FirefoxでURLを開き、Webページのタイトルとコンテンツが確認された後でURLを閉じます。
4. TestNGを使用
TestNGを使用してテストケース/スイートを実行してみましょう。
Eclipseを使用している場合は、TestNGプラグインを EclipseMarketplaceからダウンロードしてインストールできることに注意してください。
まず、新しいテストクラスを作成しましょう。
public class SeleniumWithTestNGLiveTest {
private SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
// more code goes here...
}
org.testng.annotations.BeforeSuiteの@BeforeSuiteアノテーションを使用して、SeleniumExampleクラスをインスタンス化します。 setUp()メソッドは、テストスイートがアクティブ化される直前に起動されます。
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
同様に、org.testng.annotations.AfterSuiteの@AfterSuiteアノテーションを使用して、テストスイートが完了したら、開いているブラウザーを閉じます。
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
最後に、テストを実装しましょう。
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
テストスイートが正常に完了すると、プロジェクトのtest-outputフォルダーにHTMLレポートとXMLレポートが表示されます。 これらのレポートは、テスト結果をまとめたものです。
5. 結論
このクイック記事では、JUnitとTestNGの両方を使用してSelenium3テストを作成するための簡単な紹介に焦点を当てました。
いつものように、記事のソースはGitHubで入手できます。