LoginSignup
6
2

More than 5 years have passed since last update.

Androidの自動UIテストでPermissionダイアログをスキップする(自動許可)

Last updated at Posted at 2018-07-31

概要

Androidの自動UIテストでEspressoを導入するケースが増えてきていますが、Espressoは基本的に自アプリのUIしか動かせないので、端末の設定画面が出ると固まってしまいます。
今回はAndroid Marshmallow以上で出る実行時のパーミッションリクエストダイアログをスキップする方法をご紹介します。

解決方法(例)

build.gradle

dependencies {
    ・・・
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        ・・・
}

テストコード

@Rule
public GrantPermissionRule mGrantPermissionRule =
        GrantPermissionRule.grant(
                "android.permission.RECEIVE_SMS",
                "android.permission.READ_CONTACTS",
                "android.permission.RECEIVE_MMS",
                "android.permission.READ_PHONE_STATE");

説明

Googleが導入したAndroid Testing Support Library 1.0Grant Permission Rule の項によると、GrantPermissionRuleをメンバに定義しておけば、ダイアログポップアップを完全にスキップして自動的にパーミッション許可を与えられるようです。

補足

UI AutomatorUiDeviceを使い、「許可」ボタンをテキスト検索して押すという手もあります。
他の設定画面も含めて大体それで解決します。が、以下の制限がつきまといます。

  • 複数の言語への対応が面倒(英語だと「ALLOW」だったり…)
  • コードが冗長・複雑化する

Android Studioの操作録画機能(Record Espresso Test)では、Android Studio3.1.3では上記のルールは自動記録されませんが、3.2?3.3?以降でポップアップ許可操作を録画するとGrantPermissionRuleの自動挿入されるようです(正確な対応バージョンは調べきれてません)。
なので、GoogleはTesting Support Libraryの使用を推奨しているようです。

6
2
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
6
2