美文网首页软件测试
uiautomator2 自动化

uiautomator2 自动化

作者: 小啊小狼 | 来源:发表于2020-01-17 12:06 被阅读0次

    准备工作

    要求:

    Android版本 4.4+
    Python版本3.6+
    连接手机:
    开启开发者选项,
    开启usb调试,
    连接电脑,adb devices可以看到设备号
    安装uiautomator2:python -m pip install -U uiautomator2
    验证是否连接成功:
    import uiautomator2 as u2
    driver = u2.connect() # connect to device
    print(driver.info)
    执行以上代码有正确输出
    cmd安装:
    1、安装 uiautomator2
    python -m pip install --upgrade --pre uiautomator2
    测试是否安装成功 uiautomator2 --help
    2、安装 weditor (UI Inspector)
    python -m pip install -U weditor
    在命令行运行weditor --help 确认是否安装成功
    3、电脑连接上一个手机或多个手机, 确保adb已经添加到环境变量中,执行下面的命令会自动安装本库所需要的设备端程序
    python -m uiautomator2 init
    安装提示success即可

    连接设备

    1、通过wifi,需确保同一网络
        import uiautomator2 as u2
        driver = u2.connect('10.0.0.1') # alias for u2.connect_wifi('10.0.0.1')
        print(driver.info)
    2、通过usb线
        import uiautomator2 as u2
        d = u2.connect('M9N7N15930001618') # 括号内为adb devices 获取的设备号
        print(d.info)
    

    打开weditor UI查看器

        cmd命令:python -m weditor
    
    image.png

    浏览器打开地址


    image.png

    输入设备号点击connect,connect展示绿色麦穗,表示连接成功,dump hierarchy刷新页面,可以辅助定位,比uiautomatorviewer更好用

    获取包名

    打开要测的APP
    cmd命令:uiautomator2 current
    {
            "package": "com.android.browser",
            "activity": "com.uc.browser.InnerUCMobile",
            "pid": 28478
    }
    package即为包名
    

    开始一个测试demo

    #导入要用的包
    import uiautomator2 as u2
    #连接设备
    d = u2.connect('M9N7N15930001618')  #括号内为adb devices获取的设备号
    print(d.info)  #连接成功可打印设备信息
    # 启动APP
    d.app_start("com.tencent.wework")   #括号内为要启动的APP包名
    #点击企业微信工作台
    d.xpath('//*[@text="工作台"]').click()
    #向上滑动直到小程序入口元素出现
    d(scrollable=True).scroll.to(text="@@@@ x")
    #点击小程序入口打开小程序
    d.xpath('//*[@text="@@@@ x"]').click()
    ......
    后续就是UI自动化的基本操作,定位元素,等待元素,点击元素,输入文本等等,Xpath定位元素与selenium及appium都一样,只不过uiautomator2有自己的API,大家需熟悉API后根据自己的应用场景灵活调用不同的API实现具体功能来编写测试脚本。
    

    相关文章

      网友评论

        本文标题:uiautomator2 自动化

        本文链接:https://www.haomeiwen.com/subject/bnjczctx.html