Android知识Android开发Android技术知识

Espresso 自动化测试的使用

2016-12-26  本文已影响1598人  Mark_Liu

Espresso 自动化测试使用

Espresso是一个Android UI测试框架,由三部分组成

添加加依赖库


android{
  defaultConfig{
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  }
}

dependencies{
    androidTestCompile 'com.android.support:support-annotations:24.1.1'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    }

使用Espresso测试

@RunWith(AndroidJUnit4.class)
public class UITest{

    //设置初始启动测试Activity,并启动
    @Rule
    public ActivityTestRule<TestActivity> mActivityRule
    = new ActvitiyTestRule<>(TestActivity.class);
    
    @Test
    public void testClick(){
        Espresso.onView(ViewMatchers.withId(R.id.btn)).preform(ViewActions.click()).check(ViewAssertions.matches(ViewMatchers.withText("finish")));
    }
}

ActivityTestRule 这个rule是用来测试单个Activity的,Activity将在@Test和@Before前启动

@RunWith(AndroidJUnit4.class)
public class UITest{

    //设置初始启动测试Activity,ActivityTestRule的构造函数的第三个参数是否启动Activity
    @Rule
    public ActivityTestRule<TestActivity> mActivityRule
    = new ActvitiyTestRule<>(TestActivity.class,false,false);

    @Test
    public void startActivity(){
       Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
       Intent intent = new Intent(context,TestActivity.class);
       intent.putExtra("id",2);
       mActivityRule.launchActivity(intent);
    }

    @Test
    public void testClick(){
        Espresso.onView(ViewMatchers.withId(R.id.btn)).perform(ViewActions.click()).check(ViewAssertions.matches(ViewMatchers.withText("finish")));
    }
}
Espresso
  public class CustomViewActions{
      
      
      static final class SeekBarAction implements ViewAction{
          private int progress;
          
          public SeekBarAction(int progress){
              this.progress = progress;
          }
          
          @Override
          public Matcher<View> getConstaints(){
              return allOf(ViewMatchers.isAssignableFrom(SeekBar.class),ViewMatchers.isDisplayed());
          }
          
          @Override
          public String getDescription(){
              return "this is a seek ation with SeekBar";
          }
          
          @Override
          public void perform(UiController uiController,View view){
              SeekBar seekBar = (SeekBar)view;
              seekBar.seekTo(progress);
          }
      }
  }

需要自定义 IdlingResouce,看了几篇博客描述的都有问题,建议直接参考Google官方项目 IdlingResourceSample

IdlingResource的使用已经补上,由于这篇文章篇幅已经较长,故在专门写了一篇
Espresso IdlingResource 测试延时操作的使用

ps:以上是本人对Espress的使用经验,有什么问题可以评论

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读