使用Uiautomator2进行APP自动化测试

本文介绍了如何使用Python库Uiautomator2进行安卓应用自动化测试,包括设备配置、识别元素和编写代码示例。重点展示了如何连接设备、操作界面元素并执行常见任务如点击和输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、 安装Uiautomator2

    我的环境是Python,可用pip命令安装:

pip install uiautomator2

  注:Uiautomator2的源代码: GitHub - openatx/uiautomator2: Android Uiautomator2 Python Wrapper

2、 配置设备

    首先设备连接到PC,并能够adb devices发现该设备。执行下面的命令会自动安装本库所需要的设备端程序:uiautomator-server,atx-agent

# init就是所有USB连接电脑的手机上都安装uiautomator2
python -m uiautomator2 init
 
# 指定手机安装uiautomator2, 用 --mirror
python -m uiautomator2 init --mirror --serial $SERIAL

# 嫌弃慢的话,可以用国内的镜像
python -m uiautomator2 init --mirror

注意:据说最新版的uiautomator2已不需手动配置,当代码运行 uiautomator2.connect()时,会先配置设备端。

3、 写代码之前:识别元素

    在Andorid SDK里有monitor.bat,运行它,会启动uiautomatorviewer,这是SDK自带的工具。

    也可以使用第三方工具,这里推荐 weditor,安装如下:

pip install weditor

  启动Weditor: 

python -m weditor
浏览器会自动启动一个网页 http://atx.open.netease.com,看到如下界面

 设置adb device看到的设备进行连接。

4、 正式写代码

import unittest
import uiautomator2 as u2
import time

class AppTest(unittest.TestCase):
    def EditWO(self):
        d = u2.connect()
        d.app_start('com.xxxxxx.xxxxxx')
        time.sleep(5)
        d(text='Work Order').click()    # 点击Work order菜单
        time.sleep(3)
        d(text='Completed').click()    # 点击Completed
        time.sleep(2)
        d(text='Open').click()
        time.sleep(2)
        d(text='300').click()
        time.sleep(1)
        d(text='Save').click()

        d.press('back')

    def Mapview(self):
        d = u2.connect()
        d.app_start('com.xxxxxx.xxxxxx')
        time.sleep(5)
        d.xpath(
            '//android.widget.RelativeLayout/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]').set_text('char')
        d.press('enter')
        d(text='CHARIOTOFFIRE').click()
        d(text='Cancel').click()
        d.xpath(
            '//android.widget.RelativeLayout/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[5]/android.widget.ImageView[1]').click()
        d(text='+ ADD LOCATIONS').click()
        d.xpath(
            '//androidx.recyclerview.widget.RecyclerView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.Button[3]').click()
        d.click(0.503, 0.498)
        d.xpath(
            '//androidx.recyclerview.widget.RecyclerView/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.Button[3]').click()
        d.click(0.081, 0.801)
        d.xpath(
            '//androidx.recyclerview.widget.RecyclerView/android.view.ViewGroup[3]/android.view.ViewGroup[1]/android.widget.Button[3]').click()
        d.click(0.914, 0.273)
        d(text='GET DIRECTIONS').click()
        d.press("back")


    def test_something(self):
        self.EditWO()


if __name__ == '__main__':
    unittest.main()
### 使用 uiautomator2 编写车载自动化测试脚本 #### 创建环境准备 为了使用 `uiautomator2` 进行车载系统的自动化测试,首先需要设置好开发环境。这包括安装必要的软件包以及配置连接至目标设备的方式。 确保已安装 Python 环境,并通过 pip 安装最新版本的 `uiautomator2` 库[^3]: ```bash pip install -U uiautomator2 ``` #### 初始化设备连接 初始化与待测车辆内置 Android 设备之间的 USB 或 Wi-Fi 连接。假设已经成功建立了 ADB (Android Debug Bridge) 连接,则可以通过如下命令激活 `uiautomator2`: ```python import uiautomator2 as u2 d = u2.connect() # 默认连接第一个可用设备 print(d.info) ``` 这段代码会打印出当前连接设备的信息,确认是否正确连上了车载终端[^1]。 #### 控制 UI 组件交互 利用所提供的五个核心类之一——`UiObject`, 可以方便地找到并操控界面上的对象: ```python # 查找指定文本按钮并点击 button = d(text="Start Navigation") if button.exists: button.click() else: print("Button not found") # 输入目的地地址 search_box = d(resourceId="com.example.carapp:id/searchBox") if search_box.exists: search_box.set_text("Beijing, China") ``` 这里展示了如何寻找特定的文字标签 "Start Navigation" 来触发导航功能,同时也示范了怎样向搜索框内输入文字内容。 #### 处理滚动列表项 当面对可滚动的内容区域时,比如地图上的地点建议列表,可以借助 `UiScrollable` 类来进行上下翻页直到找到所需选项为止: ```python from time import sleep scroll_view = d(scrollable=True) def find_and_click_item(target_text): while True: items = scroll_view.child_by_text(target_text=target_text) if items.exists: items.click() break else: try: scroll_view.scroll(steps=10) sleep(1) # 加入适当延时防止过快滚动错过目标 except Exception as e: raise ValueError(f"Failed to locate '{target_text}' after scrolling") from e find_and_click_item('Tiananmen Square') ``` 此函数尝试在滚动视图中查找名为 'Tiananmen Square' 的位置条目,并对其进行点击操作。如果未能立即发现该元素,则继续向下滚动直至匹配成功或抛出异常终止循环。 #### 执行复杂场景模拟 最后,在某些情况下可能还需要模拟更复杂的用户行为序列,例如切换应用程序、调整系统设置等动作。这些都可以依靠调用相应的 API 方法完成: ```python # 切换回主屏幕 d.press_home() # 开启蓝牙开关 settings_app = d.app_start("com.android.settings") bluetooth_toggle = settings_app.xpath('//android.widget.Switch[@text="ON"]|//android.widget.Switch[@text="OFF"]').get_one(timeout=5.0) current_state = bluetooth_toggle.get_text().strip().upper() desired_state = "ON" if current_state != desired_state: bluetooth_toggle.click() sleep(2) # 等待状态改变生效 assert bluetooth_toggle.get_text().strip().upper() == desired_state, f"Bluetooth should be {desired_state}" ``` 上述片段实现了打开设置应用并将蓝牙开启的功能验证逻辑。注意实际执行过程中应当加入更多的错误处理机制来提高稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zljun8210

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值