Android UITest part2- UiAutomator 簡介 與 實現6.0 M 權限彈窗操控

Android, Espresso, UiAutomator,  6.0 M Permission, UI Test

來到第二部分介紹一下UiAutomator 

UiAutomator :

  • 依賴方式:
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
  • 比較像分析介面元素的工具
  • 以下直接拿如何 操控通過permission dialog舉例:
public class EspressoTest {

    @Test
    public void onTest() {

    try {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //這裡是以進入app一開始就跳出權限提示視窗為例
            //先抓取設備屬性
            UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

            //以下原本是使用UiSelector抓取權限提示視窗上的允許字串元件,但因為多國語系的關係而放棄使用
//            UiObject button = uiDevice.findObject(new UiSelector().text("允許"));

            //此為使用抓取視窗中Button元件 為 1的位置 判斷是否存在與是否可用,執行按鈕
            UiObject button = uiDevice.findObject(new UiSelector().className("android.widget.Button").instance(1));
            if (button.exists() && button.isEnabled()) {
                button.click();
            }
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (UiObjectNotFoundException e) {
        e.printStackTrace();
    }

    }

}

其實從上面範例很簡單就可以了解,此程式庫功能比較像檢索當前畫面上的元件的控制。

搭配Espresso 解決 Espresso的一些限制。

UiSelector 所抓取的元件或搜尋方式,比較像是將所有搜尋到的物件放入陣列之中,利用相關method做更細緻的控制。

上面範例也是如何越過Android 6.0 之後官方所要求的權限提示視窗,網路上的一些回答有時候不堪用所以在此使用小聰明。

歡迎留言討論!

 

相關文章:

Android 簡易 UITest part1 - Espresso 別人沒講的依賴 與 簡易用法