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这个包

Espresso小试-LMLPHP

2. 使用ADT创建一个Android应用项目EspressoDemo, lib里加入espresso-1.1-bundled.jar

Espresso小试-LMLPHP

这个android项目我没干什么,就是加了一个按钮

Espresso小试-LMLPHP

3. 编写Test,Espresso其实是一个API,通过调用它来完成UI的操作

 package com.example.espressotest;

 import com.example.espressodemo.MainActivity;
import com.example.espressodemo.R;
import com.google.android.apps.common.testing.ui.espresso.action.ViewActions;
import com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions;
import com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers;
import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView; import android.test.ActivityInstrumentationTestCase2; @SuppressWarnings("rawtypes")
public class EspressoTest extends ActivityInstrumentationTestCase2 {
@SuppressWarnings("unchecked")
public EspressoTest() {
super(MainActivity.class);
} @Override
protected void setUp() throws Exception {
super.setUp();
getActivity();
} public void testClickButton() throws InterruptedException {
onView(ViewMatchers.withId(R.id.button1)).perform(ViewActions.click()).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
} @Override
protected void tearDown() throws Exception {
super.tearDown();
}
}

EspressoTest没干什么,就是判断添加的按钮是否存在

4. 配置AndroidManifest.xml文件,需要添加2段内容, application里添加uses-library,再添加一个instrumentation

 <application
<uses-library android:name="android.test.runner" />
</application>
 <instrumentation
android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
android:targetPackage="$YOUR_TARGET_APP_PACKAGE" />

5. 配置Runner,如下图,选择GoogleInstrumentationTestRunner

Espresso小试-LMLPHP

6. 运行测试,Espresso会自动启动AVD,安装被测APK,在AVD上执行测试

Espresso小试-LMLPHP

说到AVD,还是慢,建议及早启动

Espresso小试-LMLPHP

7. 更多信息

https://code.google.com/p/android-test-kit/

API查看https://android-test-kit.googlecode.com/git/docs/javadocs/apidocs/index.html

04-16 14:38