Android自動化測試-從入門到入門(4)uiautomatorviewer
來自: https://segmentfault.com/a/1190000004367222
我們用如下一行代碼來回顧一下之前介紹過的內容:
import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; onView(allOf(withId(id), isDisplayed())).perform(click()).check(matches(withText(text)));
還記得以上代碼的意義么?這行代碼找到了屏幕上正在顯示的指定id
的控件,對其進行了一次點擊操作,然后檢查了一下其文本為text
。
關于onView()
方法,我們需要首先知道目標控件的一些屬性值,然后再圍繞我們的目標屬性構建一個匹配規則。但有些時候,控件的屬性并不是那么明顯,或者并沒有那么容易獲取到,這時,我們可以使用Android
提供的uiautomatorviewer
工具幫助我們進行分析。
uiautomatorviewer
uiautomatorviewer
工具位于Android SDK目錄下,本文會介紹在Mac下uiautomatorviewer
的用法,其他系統下的用法相當雷同,就不一一介紹了。
在終端中切換到Android SDK的目錄下,在tools
目錄下可以看到uiautomatorviewer
工具:
運行./uiautomatorviewer
,便可以看到uiautomatorviewer
的主界面了:
很樸素對不對~
屏幕截圖
將手機連接到設備上,在手機上啟動一個需要測試的目標頁面,然后點擊uiautomatorviewer
左上角的第二個按鈕(Device Screenshot(uiautomator dump)
),便可以把當前頁面截下來了:
如上所示,我截取了一張答疑君APP登錄頁面的截圖。可以看到,uiautomatorviewer
的界面分成了3個部分:
左邊部分:顯示當前屏幕的截圖。在這個部分,我們可以對這個頁面上的各個控件做一些選中的操作。
右上角部分:顯示當前頁面的View層級。
右下角部分:顯示當前選中控件的各個屬性。
比如說,我現在想要做一個登錄的測試用例,我需要在“賬號”和“密碼” 的輸入框中輸入一些內容,然后點擊“登錄”按鈕執行登錄。首先,我選中填寫賬號的EditText
:
大家可以看到,右上角的View
層級自動定位到了我選中的EditText
上,同時右下角顯示了這個EditText
的一些屬性信息。其中,resource-id
便是這個EditText
的id
,于是我通過:
onView(withId(R.id.login_account))
便找到了這個EditText
。然后,向這個EditText
中輸入賬號信息:
onView(withId(R.id.login_account)).perform(click(), replaceText("..."), closeSoftKeyboard())
就完成了一個表單的輸入。
類似地,我們還可以通過text
的屬性來尋找我們的目標控件。我們可以根據屬性區域顯示的text
來進行匹配:
onView(withText("賬號"))
小總結
Android所提供的uiautomatorviewer
界面簡單,使用方便,對于我們的自動化測試來說是一個很好的輔助工具。對于我們之后將要介紹的UI Automator
,以及第三方測試框架Appium
,都離不開這個小工具的支持。于是,請大家趕快操練起來吧~
附錄
從這篇開始,我會在每一篇的最后附上本系列的所有文章傳送門,方便大家進行查閱:
Android自動化測試-從入門到入門(1) Hello Testing!
Android自動化測試-從入門到入門(2) Testing APIs
Android自動化測試-從入門到入門(3) Espresso入門
Android自動化測試-從入門到入門(4) uiautomatorviewer
Android自動化測試-從入門到入門(5) AdapterView的測試