LoginSignup
4
0

More than 5 years have passed since last update.

Gebでモバイルブラウザのテストをする

Last updated at Posted at 2016-12-07

はじめに

これは Geb Advent Calendar 2016の7日目の記事です。
前日は@midori004さんの「Gebで画面遷移をテストする」でした。

モバイルブラウザでのテスト

Selenium WebDriverでもよく聞く話ですが、モバイル用のサイトをテストをしたいときがあります。それをGebでどうやってやるの? という話です。

  • Geb: 1.0
  • ChromeDriver: 2.51.0 で試しています。

Selenuim WebDriverの場合

Chromeの場合は、capabilityをセットしてあげるといけます。詳しくはこのあたりのブログ(英語)をどうぞ。このサイトから引用すると、下記のような感じです。

Map<String, String> mobileEmulation = new HashMap<String, String>();
mobileEmulation.put("deviceName", "Google Nexus 5");

Map<String, Object> chromeOptions = new HashMap<String, Object>();
chromeOptions.put("mobileEmulation", mobileEmulation);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);

Gebでどうやるか。

GebのDriver生成処理

Gebでは、Driverの生成処理はGebConfig.groovyという中に書きます。
このアドベントカレンダーでもよく出てくるgeb-example-gradleGebConfigを見てみると、下記のような記述があります。

GebConfig.groovy
environments {

    // run via “./gradlew chromeTest”
    // See: http://code.google.com/p/selenium/wiki/ChromeDriver
    chrome {
        driver = { new ChromeDriver() }
    }

    // run via “./gradlew firefoxTest”
    // See: http://code.google.com/p/selenium/wiki/FirefoxDriver
    firefox {
        driver = { new FirefoxDriver() }
    }

    phantomJs {
        driver = { new PhantomJSDriver() }
    }

}

このenvironmentsというクロージャーの中身ですが、環境変数にgeb.envというキーで設定するとその対応するクロージャーが実行されます。
例えば、このサンプルだと、systemProperty "geb.env", driver // "chrome"などが入るbuild.gradleの中で定義しています。ここにchromeなどを実行すると、chrome {}で定義されているクロージャーが実行されます。

さてこのクロージャー、Groovyでは最後に評価されたものが戻り値になるので、

chrome {
        driver = { new ChromeDriver() }
}

上記のコードは純粋にChromeDriverをnewして返す、という処理になっています。
capabilityを入れる時はここに介入します。

capabilityを差し込む

差し込み方は単純で、例えば下記のようにすればOK

chrome {
        def mobileEmulation = [:]
        mobileEmulation.put("deviceName", "Google Nexus 5")

        def chromeOptions = [:]
        chromeOptions.put("mobileEmulation", mobileEmulation)
        def capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        WebDriver driver = new ChromeDriver(capabilities);
}

ちなみにこのcapability、画面サイズなどもセットできるので、他にも色々使えます。

まとめ

GebConfigのChromeDriver生成処理にcapability渡すとモバイル用ページの

明日のエントリー

明日は今日のネタを引き続いてで、モバイルとPC用のサイトを両方テストする時のTIPs書きます。

4
0
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
4
0