LoginSignup
18
15

More than 5 years have passed since last update.

Selenium2 WebDriverを使ってみる

Last updated at Posted at 2014-05-24

FirefoxDriverの代わりに、HtmlUnitDriverやChromeDriverなどなど、setUp内で生成しているWebDriverの実装を替えることで、他のブラウザーでも動くはずです。(もしかすると、CSSセレクターとか違う場合がありますが…)
あと、GoogleのサイトのDOM構成が変わったらテストが通らなくなるのでご了承下さい。

package com.github.poad.example.selenium;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * Google検索してみるサンプル
 *
 */
public class TestMain {

    private WebDriver driver;

    @Before
    public void setUp() {
        // Firefoxを起動
        this.driver = new FirefoxDriver();
    }

    @Test
    public void test() {
        // google.co.jp を開く
        this.driver.get("http://google.co.jp/");
        // 検索フォームの要素を取得
        WebElement searchForm = this.driver.findElement(By.id("lst-ib"));
        Assert.assertNotNull(searchForm);
        // 検索フォームに google と入力する
        searchForm.sendKeys("google");
        // 検索ボタン要素を取得
        WebElement searchBtn = this.driver.findElement(By.cssSelector(".jsb > center:nth-child(1) > input:nth-child(1)"));
        // 検索を実行する
        searchBtn.click();
        // 検索結果ページからGoogleのロゴ要素(のホームへのリンク要素)を取得
        WebElement homeLink = this.driver.findElement(By.cssSelector("a#logo"));
        Assert.assertEquals("a", homeLink.getTagName());

    }

    @After
    public void tearDown() {
        // Firefoxを終了
        this.driver.quit();
    }
}
18
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15