自動ブラウザテスト(3/3) WebDriverクライアントのプログラム

では最後に実際に動かしてみましょう。

クライアントライブラリは、WebDriverサーバと同じところからDLします。
selenium-java-x.xx.x.zip というのがそれで、DLしたら展開しておきます。

今度はeclipseを起動して、

  1. javaプロジェクトを作成します
  2. さきほど展開したzipファイルの中のselenium-java-x.xx.x.jarファイルを参照ライブラリーに追加します
  3. さらにlibsフォルダの以下にあるjarファイルも全部追加します(30個ぐらいあります)
  4. そしてJUnitテスト・ケース(バージョン4)を作成し、以下のコードを記述します。
import junit.framework.TestCase;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.android.AndroidDriver;

public class Test1 extends TestCase {

  public void testGoogle() throws Exception {
    WebDriver driver = new AndroidDriver();

    // And now use this to visit Google
    driver.get("http://www.google.com");

    // Find the text input element by its name
    WebElement element = driver.findElement(By.name("q"));

    // Enter something to search for
    element.sendKeys("test");

    // Now submit the form. WebDriver will find the form for us from the element
    element.submit();

    // Check the title of the page
    System.out.println("Page title is: " + driver.getTitle());
    driver.quit();
  }
}

これを実行する前に、端末のWebDriverサーバと通信するためのおまじないが要ります。

adb forward tcp:8080 tcp:8080

さぁでは、testGoogleメソッドをJUnitテスト実行してみましょう。
端末の画面を見ると、勝手にブラウザが起動して、googleに接続し「test」の検索結果が表示されれば成功です。