最近Play Framework関係の情報を色々と調べている内に、selenium2.0というWebアプリのテスト向けフレームワークがあるのを知りました。
selenium2.0は、PC上で自動でWebブラウザを操作してWebアプリケーションの動作を検証するもので、Webブラウザを操作するWebDriver APIがあります。
WebDriver APIは、Java、Python、Ruby、C#等での実装があるようです。
そのうち、使うこともあるかと思い、備忘録としてJava版を触ってみました。
1.準備
Google Project Hosting:selenium downloadから、selenium-java-2.15.0.zipとselenium-server-standalone-2.15.0.jarをダウンロードしました。
その後、Eclipseにテスト用のプロジェクトを作成し、selenium-java-2.15.0.zipのselenium-java-2.15.0.jarとlibs配下のjarファイル並びにselenium-server-standalone-2.15.0.jarをビルドパスに登録しました。
2.サンプルコード
とりあえず、
1)googleのページにアクセスする。
2)検索のテキストフィールドを取得し、”java”と入力する。
3)submitする。
4)検索結果の読み込みが終わったら画面をキャプチャしてDドライブに保存する。
5)ブラウザを閉じる。
という処理をしてみました。
ソースコードは以下のとおり。
なお、WebDriverの実装クラスは、IE、Chrome、Opera、Firefox、Android、iOS、HtmlUnit等が準備されており、それぞれの実装クラスでWebDriverインスタンスを生成することで、ブラウザをリモートすることができるようになります。
今回はselenium-server-standalone-2.15.0.jarをビルドパス(クラスパス)に入れれば使えるFireFoxDriverを使いました。
package test; import java.io.File; import org.apache.commons.io.FileUtils; 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.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class TestScan { WebDriver web; public TestScan(String url){ web=new FirefoxDriver(); web.get(url); } public void query(String str){ WebElement elem=web.findElement(By.name("q")); elem.sendKeys(str); elem.submit(); (new WebDriverWait(web, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return true; } }); } public void cap(){ try { File scrFile = ((TakesScreenshot)web).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile,new File("d:/test.png")); } catch (Exception e) { e.printStackTrace(); } } public void quit(){ web.quit(); } public static void main(String[] arg){ String url="http://www.google.co.jp/"; TestScan t=new TestScan(url); t.query("java"); t.cap(); t.quit(); System.exit(0); } }
3.実行結果
実行結果は以下のとおりです。Webページのキャプチャ画像が保存されました。
ページ全体がスキャンされることに少し驚きました。
HeartRails Capture的なサービスが結構簡単に構築できそうな感じです。
