用Android Studio的ESPRESSO自动测试APP功能

1.首先,在app的文件夹里,选择带有Android Test的包名,在其建立一个测试类,Eg:

代码:app里build.gradle类的代码需要修改的部分

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions{
exclude'LICENSE.txt'
}
}

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'
})
compile 'com.android.support:appcompat-v7:25.1.0'
testCompile 'junit:junit:4.12'
}
布局文件的代码:
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24dp"
android:text="Hello World!" />
<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24dp"
android:hint="Please name"
/>
<Button
android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"
android:onClick="sayHello"
android:text="sure"
/>
MainActivity中的代码:
public void sayHello(View view){
TextView tv1=(TextView)findViewById(R.id.tv1);
EditText et1=(EditText)findViewById(R.id.et1);
tv1.setText("Hello,"+et1.getText().toString()+"!");
}
自动测试的代码:
public class MainActivityInstrumentationTest {
private static final String STRING_TO_BE_TYPED="Peter";

@Rule
public ActivityTestRule<MainActivity> mActivityRule=new ActivityTestRule<>(MainActivity.class);

@Test
public void sayHello(){
onView(withId(R.id.et1)).perform(typeText(STRING_TO_BE_TYPED)),closeSoftKeyboard());
onView(withText("Say hello")).perform(click());
String expectedText ="Hello," + STRING_TO_BE_TYPED +"!";
onView(withId(R.id.tv1)).check(matches(withText(expectedText)));
}
}
运行结果:会将你的模拟器重新打开,然后会以最快的速度,将你制定的功能实现。
posted @ 2017-03-18 00:41  灰土豆  阅读(1187)  评论(0编辑  收藏  举报