1. 程式人生 > >UIAutomator2.0詳解(UIDevice篇----獲取UIDevice物件)

UIAutomator2.0詳解(UIDevice篇----獲取UIDevice物件)

UIAutomator2.0在UIDevice類中,提供了兩個靜態方法,用於獲取UIDevice物件。

(1)static UIDevice getInstance()
(2)static UIDevice getInstance(Instrumentation instrumentation)

方法(1)可以不用關注,官方已將該方法廢棄。即,方法(2)是唯一獲取UIDevice物件的方法。

Instrumentation mInstrumentation=InstrumentationRegistry.getInstrumentation();
UIDevice mDevice=UiDevice.getInstance
(mInstrumentation);

從方法(2)中可以看到,要獲取UIDevice物件,需要提供Instrumentation物件作為輸入引數。

Instrumentation是移動測試的白盒框架,類似於window系統的hook程式,從系統層面實現對APP的監聽。而UIAutomator2.0框架,正是基於Instrumentation框架。簡單來說,Instrumentation物件可以看做一個通過監聽獲取資訊的通道。而通過該通道獲取的裝置資訊,即是UIDevice。

InstrumentationRegistry可以看做是Instrumentation的工廠類,通過工廠類獲取Instrumentation的單例。

我們先簡單理解Instrumentation,之後將用單獨的篇幅介紹Instrumentation框架,這裡不再囉嗦。

這裡,我們用簡單的例子來測試UIDevice是否獲取成功。

程式碼如下:

package com.breakloop.u2demo;

import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
import android.util.Log;

import org.junit.Test;
import org.junit.runner.RunWith;
import
org.junit.runners.JUnit4; /** * Created by user on 2017/10/31. */ @RunWith(JUnit4.class) public class UIDeviceTest { private final String TAG=getClass().getName(); @Test public void getDevice() { UiDevice mUIDevice=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); if(mUIDevice!=null){ Log.i(TAG, "get Device successfully"); }else { Log.i(TAG, "get Device failed"); } } }

執行結果如下:

這裡寫圖片描述

這裡寫圖片描述