Selenium IDEでブラウザ操作を記録する
概要
Selenium IDEでブラウザ操作を記録する方法です。 以下の2つを利用します。
Selenium IDE のインストール
Firefoxのアドオンからインストールします。 addons.mozilla.org
ブラウザ操作の記録
- Firefoxの右上に追加された[Selenium IDE]ボタンを押下し、Selenium IDEを起動する。
- 記録したいブラウザの操作を行う。
- [ファイル] - [テストケースをエクスポート] - [Java / JUnit4 / WebDriver]から、テストコードを出力する。
テストコード
package com.example.tests; import static org.junit.Assert.fail; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumTest { private WebDriver driver; private String baseUrl; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); @Before public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "https://www.google.co.jp/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testSeleniumT() throws Exception { // Googleからはてなを表示 driver.get(baseUrl + "/search?q=%E3%81%AF%E3%81%A6%E3%81%AA&ie=utf-8&oe=utf-8&hl=ja"); driver.findElement(By.linkText("はてな")).click(); } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } }