1.gradle配置
加入以下库:
androidTestCompile 'com.android.support.test:runner:0.+' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.+' androidTestCompile 'com.android.support:support-annotations:23+'
在defaultconfig下加入:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"用于指定这个类来解析和执行所有测试用例
2.测试类:
package com.example.zhouyi.unittest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; /** * Created by zhouyi on 16/7/19. */ @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>( MainActivity.class); @Test public void have_view_text_add() { onView(withId(R.id.btntest)) .check(matches(withText("add"))); } }
测试类前面加上RunWith注解
一个测试类可以测试多个activity,这个测试类中需要测试哪些activity,就要配置多少个对应的activityrule
onView方法设置需要观察的view,这个view可以由withid(以id索引)或withtext(以内容查找)来指定
check:指定按什么规则来检测view,比如上例中检测button里的文字是否是add
注意:要执行的测试方法中测试的activity必须启动才能测试,比如上例中,执行have_view_test_add,要btntest所在的mainactivity启动才行
其他测试方法还有:
所有text为add的view中,有一个显示出来的
onView(withText("add")).check(matches(isDisplayed()));
edttest对应的edittext执行三部操作:清空,写入字符串qf,关闭软键盘,然后点击btntest对应的按钮,最后判断edittext里面的内容是否为qfok
onView(ViewMatchers.withId(R.id.edttest)).perform(clearText(),typeText("qf"), ViewActions.closeSoftKeyboard()); onView(ViewMatchers.withId(R.id.btntest)).perform(click()); onView(ViewMatchers.withId(R.id.edttest)).check(matches(withText("qfok")));
其他测试方法可以参考github:
https://github.com/chiuki/espresso-samples