初めてのselenium
関Java2012年10月で@jyukutyoさんの発表を見てseleniumに挑戦することにしました。
まずはテスト対象のweb画面を作成。
1.ここでnameテキストに「selenium」と入力して、「greet」ボタンをクリック
2.この画面でh1タグに「Hello selenium」と表示
とりあえず、これだけのことをテストコードを書いて実行する。
web画面の作成は、ここに記事(メモ)を書きました。
職場で使いたいのでEclipseを使用することに、まず必要な環境作成
Downloads - selenium - Browser automation framework - Google Project Hostingよりselenium-java.zipファイルをdownload
EclipseでJavaProjectを作成して、downloadしたjarファイルをクラスパスに追加
JUnit Test Caseのファイルを新規作成して、以下の内容を実装(@jyukutyoさんはTestNGを使用していましたが、とりあえず今回はJUnitを使用)
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class TestHello2 { @Test public void test() throws IOException { WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:8080/HelloSample/faces/Hello.xhtml"); // ★1最初の画面起動 final int timeoutInSeconds = 5; WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds); wait.until(ExpectedConditions.titleIs("Hello")); WebElement name = driver.findElement(By.id("form1:name")); name.sendKeys("selenium"); // ★2ここでnameテキストに「selenium」と入力 WebElement greetBtn = driver.findElement(By.id("form1:greet")); greetBtn.click(); // ★3「greet」ボタンをクリック wait.until(ExpectedConditions.titleIs("Greeting")); // ★4画面遷移をtitleで確認 WebElement element = driver.findElement(By.tagName("h1")); Assert.assertEquals(element.getText(), "Hello selenium"); // ★5h1タグの内容を検証 // ★この時点の画面をスクリーンショットをとって保存 File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(file, new File("test.png")); driver.close(); } }
テストで作成した画面のスクリーンショット
テストも無事グリーンに
コードはmy first selenium (for HelloSample) · GitHubにあります。
次はできればこのテストをGroovy,Gebでも挑戦したい、eclipseを使って、、、
同じテストをGebで試したかったが、エラーが発生中、><、初めてGebに挑戦 - tomoTakaの日記
同じテストをGebで再度挑戦
初めてGebに挑戦2 - tomoTakaの日記