「Selenium」モーダルダイアログをテストする
Selenium WebDriver でモーダルダイアログをテストするテストコード書いてみました。
※ Selenium のバージョン等は以下のエントリと同じです。ただ、今回は Web ブラウザに Internet Explorer 11 を使うことにしました。
・プログラム日記
http://a4dosanddos.hatenablog.com/entries/2014/04/23
Internet Explorer のドライバは、以下からダウンロードしておきます。
・Downloads
http://docs.seleniumhq.org/download/
では、さっそくですが、以下がテストコードになります。
■ ModalDialogTest.java
package test; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie.InternetExplorerDriver; public class ModalDialogTest { public static void main(String[] args) { WebDriver driver = new InternetExplorerDriver(); driver.get("http://localhost/selenium/ModalDialog1.html"); // 親ウィンドウのハンドルを取得しておく String currentWindow = driver.getWindowHandle(); WebElement b1 = driver.findElement(By.name("b1")); b1.click(); // 現在開かれているウィンドウのハンドルを取得する Set<String> windows = driver.getWindowHandles(); System.out.println(windows.size()); for (String window : windows) { // 親ウィンドウではないハンドルであればスイッチ ( 今回の場合、ウィンドウは 2 つしかないので・・・ ) if (!currentWindow.equals(window)) { driver.switchTo().window(window); } } WebElement t1 = driver.findElement(By.name("t1")); t1.sendKeys("hoge"); driver.quit(); } }
WebDriver#getWindowHandles で現在開かれているウィンドウのハンドルが取得して、ダイアログのハンドルを WebDriver#switchTo に渡してフォーカスする画面を切り替えてやってます。
・WebDriver
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html
・WebDriver.TargetLocator
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.TargetLocator.html
テストページは以下になります。
■ ModalDialog1.html
<html> <head> <script type="text/javascript"> <!-- function test() { showModalDialog("ModalDialog2.html", "", ""); } --> </script> </head> <body> <input type="button" name="b1" value="b1" onclick="test()"/> </body> </html>
■ ModalDialog2.html
<html> <body> <input type="text" name="t1"/> </body> </html>
あと、テストコードを実行する際は、以下のドキュメントに書いてますが、システムプロパティ "webdriver.ie.driver" に IE のドライバを指定してやってください ( もちろん、コード内で指定してもいけるはずです )。
・InternetExplorerDriver - selenium - Everything you wanted to know about the Internet Explorer driver - Browser automation framework - Google Project Hosting
https://code.google.com/p/selenium/wiki/InternetExplorerDriver
「Selenium でモーダルダイアログのテスト」情報的には以下にありますね。
・Issue 284 - selenium - Support for window.showModalDialog - Browser automation framework - Google Project Hosting
https://code.google.com/p/selenium/issues/detail?id=284
WebDriver#sendKeys が遅いですね・・・以上です。