Espresso開源了,那就試着用一下,
1. 下載Espresso
Espresso沒有提供單獨的jar包下載,建議clone整個項目或者下載zip包
git clone https://code.google.com/p/android-test-kit/
或從這里下載:https://code.google.com/p/android-test-kit/source/browse/
我們一般用espresso-1.1-bundled.jar這個包

2. 使用ADT創建一個Android應用項目EspressoDemo, lib里加入espresso-1.1-bundled.jar

這個android項目我沒干什么,就是加了一個按鈕

3. 編寫Test,Espresso其實是一個API,通過調用它來完成UI的操作
1 package com.example.espressotest; 2 3 import com.example.espressodemo.MainActivity; 4 import com.example.espressodemo.R; 5 import com.google.android.apps.common.testing.ui.espresso.action.ViewActions; 6 import com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions; 7 import com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers; 8 import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView; 9 10 import android.test.ActivityInstrumentationTestCase2; 11 12 @SuppressWarnings("rawtypes") 13 public class EspressoTest extends ActivityInstrumentationTestCase2 { 14 @SuppressWarnings("unchecked") 15 public EspressoTest() { 16 super(MainActivity.class); 17 } 18 19 @Override 20 protected void setUp() throws Exception { 21 super.setUp(); 22 getActivity(); 23 } 24 25 public void testClickButton() throws InterruptedException { 26 onView(ViewMatchers.withId(R.id.button1)).perform(ViewActions.click()).check(ViewAssertions.matches(ViewMatchers.isDisplayed())); 27 } 28 29 @Override 30 protected void tearDown() throws Exception { 31 super.tearDown(); 32 } 33 }
EspressoTest沒干什么,就是判斷添加的按鈕是否存在
4. 配置AndroidManifest.xml文件,需要添加2段內容, application里添加uses-library,再添加一個instrumentation
1 <application 2 <uses-library android:name="android.test.runner" /> 3 </application>
1 <instrumentation 2 android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner" 3 android:targetPackage="$YOUR_TARGET_APP_PACKAGE" />
5. 配置Runner,如下圖,選擇GoogleInstrumentationTestRunner

6. 運行測試,Espresso會自動啟動AVD,安裝被測APK,在AVD上執行測試

說到AVD,還是慢,建議及早啟動

7. 更多信息
https://code.google.com/p/android-test-kit/
API查看https://android-test-kit.googlecode.com/git/docs/javadocs/apidocs/index.html
