android stuido 上uiautomator2.0的使用

因为公司测试部门有Android自动化测试的需求,就写一篇简单的实现自动化测试qq的demo。

1.新建工程 file-》new-》new project-》next—》next-》add no activity

android stuido 上uiautomator2.0的使用

2.打开build.gradle文件

android stuido 上uiautomator2.0的使用

3.添加远程依赖   compile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'

android stuido 上uiautomator2.0的使用android stuido 上uiautomator2.0的使用

4,刷新依赖

android stuido 上uiautomator2.0的使用android stuido 上uiautomator2.0的使用

5写测试代码

android stuido 上uiautomator2.0的使用android stuido 上uiautomator2.0的使用

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {


    private UiDevice device;

    @Test
    public void useAppContext() throws Exception {
        Context context = InstrumentationRegistry.getContext();
        Intent launchIntent = new Intent();
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //启动应用
        launchIntent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.SplashActivity"));
        context.startActivity(launchIntent);
        // 启应用
//        Runtime.getRuntime().exec("am start - com.tencent.mobileqq/com.tencent.mobileqq.activity.SplashActivity");
        sleep(3000);

        // 点击 "动态" tab
        UiDevice device = UiDevice.getInstance(getInstrumentation());
        int height = device.getDisplayHeight();
        int width = device.getDisplayWidth();
        device.click(width - 50, height - 50);
        sleep(1000);

        // 点击 "好友动态" 按钮
        UiObject obj_1 = new UiObject(new UiSelector().description("点击进入好友动态"));
        obj_1.click();
        sleep(2000);

        // 点击 左上角返回 "动态"按钮
        UiObject obj_2 = new UiObject(new UiSelector().resourceId("com.tencent.mobileqq:id/ivTitleBtnLeft"));
        String text = obj_2.getText();
        obj_2.click();
        sleep(1000);

        // 点击菜单键
        device.pressMenu();
        sleep(1000);

        // 点击退出qq
        UiObject obj_3 = new UiObject(new UiSelector().text("退出QQ"));
        obj_3.click();
        sleep(1000);

        // 点击确定
        UiObject obj_4 = new UiObject(new UiSelector().text("确定"));
        obj_4.click();
    }
}

6,书写完成就可以真机测试了,先保证手机打开了开发者模式然后通过usb线连接电脑。

7.编辑edit config设置运行测试类,设置如图所示。

android stuido 上uiautomator2.0的使用android stuido 上uiautomator2.0的使用

android stuido 上uiautomator2.0的使用

8,选择测试类 运行

android stuido 上uiautomator2.0的使用

9.选择要测试的机器,点击ok 就可以跑起测试文件了

android stuido 上uiautomator2.0的使用android stuido 上uiautomator2.0的使用