Espresso 是 Google 官方提供的一個易於測試 Android UI 的開源框架 , 於2013年10月推出它的 released 版本 , 目前最新版本已更新到2.x . 而且在AndroidStudio 2.2 預覽版中已經默認集成該測試庫 .html
Espresso 由如下三個基礎部分組成:android
ViewMatchers - 在當前View層級去匹配指定的View .git
ViewActions - 執行Views的某些行爲,如點擊事件 .github
ViewAssertions - 檢查Views的某些狀態,如是否顯示 .網絡
Espresso 測試app
onView(ViewMatcher) //1.匹配View .perform(ViewAction) //2.執行View行爲 .check(ViewAssertion); //3.驗證View
目前AndroidStudio的2.2預覽版已經默認集成:框架
build.gradle
配置以下:異步
apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.sample.espresso" minSdkVersion 14 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile 'junit:junit:4.12' }
得到Viewide
withId方式單元測試
onView(withId(R.id.my_view))
withText方式
onView(withText("Hello World!"))
執行View行爲
點擊
onView(...).perform(click());
文本內容輸入
onView(...).perform(typeText("Hello"), click());
scrollTo 滑動
onView(...).perform(scrollTo(), click());
檢驗View
檢驗View的文本內容
onView(...).check(matches(withText("Hello!")));
檢驗View的顯示狀態
onView(...).check(matches(isDisplayed()));
示例代碼:
簡單的登錄場景測試
@RunWith(AndroidJUnit4.class) public class LoginUITest { @Rule public ActivityTestRule<LoginActivity> rule=new ActivityTestRule<LoginActivity>(LogingActivity.class,true); @Test public void login(){ //login onView(withId(R.id.userName)).perform(typeText("Jack"),closeSoftKeyboard()); onView(withId(R.id.password)).perform(typeText("1234"),closeSoftKeyboard()); onView(withText("登陸")).perform(click()); //verify onView(withId(R.id.content)).check(matches(isDisplayed())); } }
歡迎進入本文的重點內容。
1. 使用IdlingResource
一般,咱們實際的應用當中會有不少異步任務,例如網絡請求,圖片加載等,可是Espresso並不知道你的異步任務何時結束,因此須要藉助於IdlingResource .
這裏須要注意的是,若是你是經過AsyncTask或者AsyncTaskCompat方式的異步任務,Espresso已經處理好,並不須要去額外的處理。
第一步:添加依賴庫
compile 'com.android.support.test.espresso:espresso-idling-resource:2.2.2'
第二步:實現IdlingResource接口 .
public interface IdlingResource { /** * 用來標識 IdlingResource 名稱 */ public String getName(); /** * 當前 IdlingResource 是否空閒 . */ public boolean isIdleNow(); /** 註冊一個空閒狀態變換的ResourceCallback回調 */ public void registerIdleTransitionCallback(ResourceCallback callback); /** * 通知Espresso當前IdlingResource狀態變換爲空閒的回調接口 */ public interface ResourceCallback { /** * 當前狀態轉變爲空閒時,調用該方法告訴Espresso */ public void onTransitionToIdle(); } }
下面咱們以一個示例來講明:
場景:假設當前咱們須要測試用戶的頭像的是否正常顯示。
Activity
代碼
public class AvatarActivity extends AppCompatActivity{ private ImageView mAvatar; public static SimpleIdlingResource sIdlingResource=new SimpleIdlingResource(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_idling_resource); mAvatar= (ImageView) findViewById(R.id.avatar); //App 開始進入忙碌狀態 ,等待通知 sIdlingResource.decrement(); //開始加載頭像圖片 Glide.with(this).load("https://avatars2.githubusercontent.com/u/2297803?v=3&s=460").into(new GlideDrawableImageViewTarget(mAvatar) { @Override public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) { super.onResourceReady(resource, animation); //加載完畢後,將App設置成空閒狀態 sIdlingResource.increment(); } }); } }
SimpleIdlingResource
代碼
public final class SimpleIdlingResource implements IdlingResource { private final AtomicInteger counter = new AtomicInteger(0); private volatile ResourceCallback resourceCallback; @Override public String getName() { return "SimpleIdlingResource"; } /** * 若是counter的值等於0,說明當前是空閒狀態 */ @Override public boolean isIdleNow() { return counter.get() == 0; } @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) { this.resourceCallback = resourceCallback; } /** * counter的值增加方法 */ public void increment() { counter.getAndIncrement(); } /** *counter的值減小方法 */ public void decrement() { int counterVal = counter.decrementAndGet(); if (counterVal == 0) { // 執行onTransitionToIdle()方法,告訴Espresso,當前是空閒狀態。 if (null != resourceCallback) { resourceCallback.onTransitionToIdle(); } } if (counterVal < 0) { throw new IllegalArgumentException("Counter has been corrupted!"); } } }
IdlingResourceTest
代碼
@RunWith(AndroidJUnit4.class) public class IdlingResourceTest { @Rule public ActivityTestRule<AvatarActivity> rule=new ActivityTestRule<>(AvatarActivity.class,true); @Before public void registerIdlingResource(){ Espresso.registerIdlingResources(rule.getActivity().sIdlingResource); } @Test public void avatarDisplayed(){ onView(withId(R.id.avatar)).check(matches(isDisplayed())); } @After public void unregisterIdlingResource() { Espresso.unregisterIdlingResources( rule.getActivity().sIdlingResource); } }
另外,Espresso
提供了一個實現好的CountingIdlingResource
類,因此若是沒有特別需求的話,直接使用CountingIdlingResource
便可。
2.建立一個自定義 Espresso matcher
目前Espresso
提供的方法基本上能夠知足你的測試需求,以下圖所示:
若是你須要對自定義的View中某個自定義屬性進行測試的話,你能夠建立一個自定義的Matcher
public static Matcher<View> isMoved() { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("is moved"); } @Override public boolean matchesSafely(View view) { return ((CustomView)view).isMoved(); } }; }
3.如何處理動畫
系統動畫:
爲了不動畫線程運行期間對Espresso
測試產生的影響,官方強烈建議關閉系統動畫。如圖所示:
自定義動畫:
對於自定義動畫,開發者能夠藉助如下代碼去控制動畫的開和關。
該方法能夠監聽系統動畫的開關事件,這是一個值得推薦的作法,不只僅是在Espresso測試中。
boolean animationEnabled=true; if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){ try { if (Settings.Global.getFloat(getContentResolver(),Settings.Global.ANIMATOR_DURATION_SCALE)==0.0f){ animationEnabled=false; } } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } }
4.優雅的IntentTest
普通的方式
@Rule public ActivityTestRule<MainActivity> rule=new ActivityTestRule<MainActivity>(MainActivity.class){ @Override protected Intent getActivityIntent() { Intent result=new Intent(...); result.putExtra(...) return result; } };
若是使用普通的方式,那麼該單元測試類下的全部測試都是基於該Intent
啓動的Activity
,這樣顯然不夠靈活。
優雅的方式
@Rule public ActivityTestRule<MainActivity> rule=new ActivityTestRule<MainActivity>(MainActivity.class,true,false);//第三個參數爲是否自動運行Activity public void myTest(){ Intent result=new Intent(...); result.putExtra(...); rule.launchActivity(result); }
5.保證測試的獨立性
一般使用Espresso進行UI測試的時候,你並不指望去測試網絡或者遠程的服務相關的東西,因此,你能夠藉助於Espresso Intent
,Mockito for mocking
,以及依賴注射、Dagger2
。
總之,儘可能去分離那些不屬於UI層面的內容。
例如:你須要某個按鈕的點擊事件進行測試,可是該按鈕的點擊後,會跳轉到別的Activity
,但是你不但願去測試別的Activity
,那麼這裏就能夠經過攔截Intent
來解決。
首先你須要添加IntentTest依賴庫:
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'
InterceptIntentTest
示例代碼
@RunWith(AndroidJUnit4.class) public class InterceptIntentTest { @Rule public IntentsTestRule<MainActivity> rule=new IntentsTestRule<>(MainActivity.class); @Before public void stubCameraIntent(){ // 模擬一個ActivityResult Instrumentation.ActivityResult result = createImageCaptureActivityResultStub(); //攔截MediaStore.ACTION_IMAGE_CAPTURE,並返回模擬後的result intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result); } @Test public void takePhoto_cameraIsLaunched(){ onView(withId(R.id.button_take_photo)).perform(click()); intended(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)); ... } private Instrumentation.ActivityResult createImageCaptureActivityResultStub() { // Create the ActivityResult, with a null Intent since we do not want to return any data // back to the Activity. return new Instrumentation.ActivityResult(Activity.RESULT_OK, null); } }
6.避免直接複製粘貼test代碼
舉個簡單的例子。
onData(allOf(is(instanceOf(Map.class)),hasEntry(equalTo("STR"),is("item:50")))).perform(click());
以上這段代碼是匹配列表中符合條件的item,並執行執行點擊事件,測試也正常,一樣這段代碼也被複制到了其餘的測試方法中使用,
這時,設想一下,若是你的adapter
中的數據源改爲了cursor
或者其餘,因而悲催了,你須要修改不少地方,顯然,這不是一個合格的CV戰士。
因此,咱們須要對以前那行代碼進行改裝:
@Test public void myTest(){ onData(withItemContent("item:50")).perform(click()); } public static Matcher<? extends Object> withItemContent(String expectedText) { .... }
很簡單,只需將可能變化的部分抽出來便可。
7.如何測試View的位置
如圖所示:
8.自定義錯誤日誌
默認的錯誤日誌打印信息比較多,如圖:
若是你只想顯示你關心的日誌信息,你能夠自定義FailureHandler:
Espresso.setFailureHandler(new CustomFailureHandler());
Advanced Espresso - Google I/O 2016
Espresso 官方文檔
Android user interface testing with Espresso - Tutorial
googlesamples/android-testing