Android 开发 Espresso (执行操作View Actions)

Android 开发 Espresso (执行操作View Actions)

在视图上执行操作(View Actions)

当为目标视图找到了合适的适配器后,你将可以通过 ​perform​方法在该视图上执行 ​ViewAction​

比如点击视图

onView(…).perform(click());

你可以在一个 perform 方法中执行多个操作

onView(…).perform(typeText("Hello"), click());

我们展示一一下目前所有的视图操作

Text类型

  • typeText 获得焦点并注入文本
  • typeTextIntoFocusedView在已获得焦点的View上注入文本
  • clearText 文本清除
  • replaceText String 文本替换
 @Test
    public void  testText() throws  Exception{

        ViewInteraction editText
         = onView(withId(R.id.espresso_demo_editText));

        editText.perform(typeText("TiaoPi")
                ,clearText()
                ,typeText("TiaoPi22222222")
                ,typeTextIntoFocusedView("TiaoPi")
                ,replaceText("XinXinXinTiaoPi"));

    }

Click/Press 类型

  • click点击
  • doubleclick双击
  • longclick长按
  • pressIMEActionButton()
  • pressKey([int/EspressoKey]) 物理按键
  • pressMenuKey菜单键 点击
  • pressBack后退键 点击
  • closeSoftKeyboard关闭键盘
  • openLink 链接点击

演示最常用的

  @Test
    public void clickTest() throws  Exception{

        ViewInteraction button8 = onView(withId(R.id.button8));
        ViewInteraction button9 = onView(withId(R.id.button9));

        button8.perform(click(),longClick());
        button9.perform(doubleClick());
    }

Gestures类型

  • scrollTo 滑动到指定View
  • swipeXX 向XX方向滑动
scrollTo()
swipeLeft()
swipeRight()
swipeUp()
swipeDown()

我们写个List测试一下

  @Test
    public void testGestures(){

        ViewInteraction expressoH = onView(withId(R.id.expresso_RecyclerView_h));
        ViewInteraction expressoV = onView(withId(R.id.expresso_RecyclerView_v));

        expressoH.perform(swipeRight());
        expressoH.perform(swipeLeft());

        expressoV.perform(swipeUp(),swipeDown());

        //休眠再去找这个
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        expressoV
                .perform(RecyclerViewActions.actionOnItem(
                        hasDescendant(withText(String.valueOf(20))), scrollTo()));

    }

关于RecyclerView

需要加入espresso-contrib进行测试

   androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.0') {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude module: 'recyclerview-v7'
    }

你可能感兴趣的:(Android 开发 Espresso (执行操作View Actions))