1,首先创建一个Android Application工程, 参考:http://blog.csdn.net/seaee/article/details/51993778
2,下载Espresso依赖的jar文件。https://github.com/oscarxie/android-test-kit/tree/master/bin/espresso-standalone。下载后将Jar文件添加到工程的libs目录下,然后通过Add External Jar 引入到工程当中。
3,创建一个新的测试包,在测试包下面创建一个测试类。类似:【注意】在这里如果需要确认View id,可以通过tools/ 下面的uiautomation viewer 来确认。
package com.example.bimhdespresso;
import com.example.bimhdtest01.MainActivity;
import com.example.bimhdtest01.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);
}
protected void setUp() throws Exception {
super.setUp();
getActivity();
}
public void testString() throws InterruptedException{
//onView(ViewMatchers.withId(R.id.action_bar)).perform(ViewActions.click()).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
onView(ViewMatchers.withId(R.id.action_bar)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
onView(ViewMatchers.withText("Hello world Wayne!!")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
protected void tearDown() throws Exception{
super.tearDown();
}
}
4,写完测试类之后,找到工程下有一个AndroidManifest.xml 文件,添加两个标签。在<application>标签中添加
<uses-library
android:name="android.test.runner" />
再在外面添加一个<instrumentation>标签:
<instrumentation
android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
android:targetPackage="com.example.bimhdtest01" />
5,保存上述修改之后,右键工程,run as - Run Configuration - 配置Runner,如下图,选择GoogleInstrumentationTestRunner
6,运行测试。
参考文章:
http://www.cnblogs.com/oscarxie/p/3521695.html
http://blog.csdn.net/itfootball/article/details/22741571