Android, Espresso, UiAutomator, 6.0 M Permission, UI Test
今天來介紹一下 Android UI Test 相關介紹
目前我所使用的是Espresso與UiAutomator兩種
Espresso:
- 依賴方式:
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies { //Espresso相關依賴 androidTestCompile 'com.android.support:support-annotations:24.1.1' androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:1.0.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.0' //@標籤使用的依賴 androidTestImplementation 'androidx.test:core:1.1.0' androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test:runner:1.1.0' }
我使用的是
com.android.support:appcompat-v7:26.0.2
其他版本請斟酌調整依賴版本
- 語法由三個部分組成:
- ViewMachers:尋找View (通常使用R.id)
- ViewActions: 執行交互事件 (例如: click(), TypeText(String)等...)
- ViewAssertions:檢驗測試結果 (withText(String) 驗證字串等...)
- 建構方式:
public class EspressoTest { @Rule //測試代碼開始之前啟用的活動 (這裡是明確當下Activity,使用ActivityTestRule類) public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class); @Before public void onStart() { //在執行@Berfore之前會初始化規則,並經過(onCreate, onStart, onResume) //開始測試之前會執行,通常用於初始化物件等。 } @Test public void onTest() { //正式進入UI Test 的活動 try { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //這裡是執行Activity中轉跳Fragment的Method mActivityTestRule.getActivity().toFragment(HomeFragment.newInstance()); //進入HomeFragment 頁面 //ViewMachers onView 尋找所需要找的View 通常使用Rid (這裡找的是一個Button元件) onView(withId(R.id.home_start)) //ViewActions perform 與該View交互作用 (這裡是指按下該Button元件) .perform(click()) //ViewAssertions check 驗證該元件字體是否為"isClick" .check(ViewAssertions.matches(ViewMatchers.withText("isClick"))); } } catch (UiObjectNotFoundException e) { e.printStackTrace(); } } @After public void onFinish() { //經過每個@Test方法之後被調用 //測試結束後所要執行Method //執行完畢後會經過,活動將被銷毀(onPause,onStop,onDestroy) } }
以上是簡易的使用介紹,詳細規則用法請搜尋相關文章!
歡迎留言討論!
相關文章: