自动化框架(Appium)

一、Appium 核心特点

1. 跨平台兼容性

  • 多平台支持:同时支持 iOS 和 Android 两大移动操作系统。
  • 多应用类型覆盖:
    • 原生应用(如 iOS 的.ipa、Android 的.apk)
    • 混合应用(WebView + 原生组件)
    • 移动网页(Safari、Chrome 等移动端浏览器)
  • 一次编写,多平台运行:同一套测试代码可在 iOS 和 Android 上复用(需注意平台特定差异)。

2. 编程语言无关性

  • 支持主流编程语言:Java、Python、JavaScript(Node.js)、C#、Ruby 等。
  • 统一 API 接口:无论使用哪种语言,Appium 提供一致的 API 设计(基于 WebDriver 协议),降低学习成本。

3. 无需修改应用代码

  • 黑盒测试:测试过程中无需重新编译或修改被测应用的源代码,保证测试环境与生产环境一致性。
  • 兼容性强:适用于第三方应用或无法获取源码的应用。

4. 标准协议驱动

  • WebDriver 协议:基于 W3C WebDriver 标准(前身为 JSON Wire Protocol),与 Selenium WebDriver 同源,便于 Web 和移动测试技术栈整合。
  • HTTP 通信:Appium 服务器与测试客户端通过 HTTP 接口通信,支持分布式测试架构。

5. 设备与环境灵活性

  • 真实设备与模拟器 / 仿真器:
    • 支持物理设备(如 iPhone、Android 手机)
    • 支持模拟器(iOS Simulator)和仿真器(Android Emulator)
  • 云测试平台集成:可对接 Sauce Labs、BrowserStack 等云测试服务,实现跨设备自动化测试。

6. 丰富的元素定位与交互方式

  • 多种定位策略:ID、XPath、类名、内容描述(Accessibility ID)、UI Automator(Android)、XCUITest(iOS)等。
  • 复杂操作支持:
    • 触摸事件(点击、长按、滑动、捏合缩放)
    • 键盘输入
    • 手势操作
    • 多设备协同操作

7. 与测试框架集成

  • 测试框架兼容性:可与 JUnit、TestNG(Java)、pytest(Python)、Mocha(JavaScript)等主流测试框架结合。
  • 断言库支持:搭配 AssertJ、Hamcrest、PyHamcrest 等断言库编写验证逻辑。
  • CI/CD 集成:无缝接入 Jenkins、GitLab CI、GitHub Actions 等持续集成工具。

8. 高级功能扩展

  • Appium 扩展插件:
    • Appium Inspector:可视化元素定位工具
    • Appium Doctor:环境配置检查工具
    • Appium Pro:企业级支持版本
  • 性能监控:可集成工具监控应用 CPU、内存、网络流量等性能指标。
  • 并行测试:通过 Appium Grid 实现多设备同时执行测试,提升效率。

9. 社区与生态支持

  • 活跃开源社区:GitHub 上超 1.5 万颗星,社区贡献持续更新。
  • 文档完善:官方文档提供详细教程和 API 参考。
  • 第三方工具集成:与 Allure(测试报告)、Applitools(视觉测试)等工具无缝对接。

10. 平台特定支持

  • Android:支持 UiAutomator2、Espresso 等自动化引擎,可测试 Android 特有的 UI 组件。
  • iOS:集成 XCUITest 框架,支持 iOS 手势、通知、权限管理等功能测试。

二、Appium 环境搭建(Python 示例)

1. 系统要求

环境 要求
操作系统 Windows 10/11、macOS(推荐)或 Linux
Python Python 3.7+(推荐 3.9+),需配置python或python3命令
Node.js 14.x+(推荐 LTS 版本),用于安装 Appium 服务器
Android 开发 Android SDK(API 23+)、Android Studio(可选)
iOS 开发 macOS 系统、Xcode 11+、CocoaPods(iOS 自动化必需)

2. 安装 Appium 服务器

2.1 安装 Node.js 和 npm

  • macOS/Linux:通过 Homebrew 安装

    1. bash
    2. brew install node
  • Windows:从Node.js 官网下载安装包,默认勾选 npm。

2.2 全局安装 Appium

  1. bash
  2. npm install -g appium
  • 验证安装:

    1. bash
    2. appium -v # 输出版本号(如2.0.0)即安装成功

2.3 安装 Appium 驱动(按需)

Appium 2.0 后需单独安装驱动:

  1. bash
  2. \# Android驱动(UiAutomator2
  3. appium driver install uiautomator2
  4. \# iOS驱动(XCUITest
  5. appium driver install xcuitest

3. 安装 Appium Python 客户端

  1. bash
  2. pip install Appium-Python-Client
  • 验证安装:

    1. bash
    2. python -c "import appium; print(appium.\_\_version\_\_)"

4. Android 环境配置

4.1 安装 Android SDK

  • 下载并安装Android Studio
  • 启动 Android Studio,打开SDK Manager(工具 → SDK Manager)
  • 安装以下组件:
    • Android SDK Platform-Tools
    • Android SDK Build-Tools
    • 至少一个 Android API 版本(如 Android 11)
    • Android Emulator(可选,用于模拟器测试)

4.2 配置环境变量

  • Windows:

    1. bash
    2. ANDROID\_HOME=C:\\Users\\YourName\\AppData\\Local\\Android\\Sdk
    3. PATH=%PATH%;%ANDROID\_HOME%\\tools;%ANDROID\_HOME%\\platform-tools
  • macOS/Linux:

    1. bash
    2. export ANDROID\_HOME=$HOME/Library/Android/sdk
    3. export PATH=$PATH:$ANDROID\_HOME/tools:$ANDROID\_HOME/platform-tools

4.3 验证 Android 配置

  1. bash
  2. adb version # 输出Android Debug Bridge版本

iOS 环境配置(仅 macOS)

5.1 安装 Xcode

从 App Store 下载并安装 Xcode,安装后启动一次以完成初始化。

5.2 安装 CocoaPods

  1. bash
  2. sudo gem install cocoapods

5.3 配置 Xcode 命令行工具

  1. bash
  2. sudo xcode-select --switch /Applications/Xcode.app

启动 Appium 服务器

6.1 直接启动(命令行)

  1. bash
  2. appium

6.2 使用 Appium Desktop(推荐)

  • 从Appium Desktop 官网下载对应系统的安装包
  • 启动 Appium Desktop,点击 “Start Server” 按钮

验证环境配置

7.1 创建测试脚本 test_calculator.py

  1. python 运行
  2. from appium import webdriver
  3. import time
  4. \# Android计算器测试示例
  5. desired\_caps = {
  6. "platformName": "Android",
  7. "platformVersion": "11", # 替换为你的Android版本
  8. "deviceName": "emulator-5554", # 替换为你的设备名称(adb devices查看)
  9. "appPackage": "com.android.calculator2",
  10. "appActivity": "com.android.calculator2.Calculator",
  11. "automationName": "UiAutomator2",
  12. "newCommandTimeout": 60 # 命令超时时间
  13. }
  14. driver = webdriver.Remote('http://localhost:4723/wd/hub', desired\_caps)
  15. try:
  16. \# 点击数字5
  17. driver.find\_element('id', 'com.android.calculator2:id/digit\_5').click()
  18. \# 点击加号
  19. driver.find\_element('id', 'com.android.calculator2:id/op\_add').click()
  20. \# 点击数字3
  21. driver.find\_element('id', 'com.android.calculator2:id/digit\_3').click()
  22. \# 点击等号
  23. driver.find\_element('id', 'com.android.calculator2:id/eq').click()
  24. time.sleep(1)
  25. result = driver.find\_element('id', 'com.android.calculator2:id/result').text
  26. print(f"计算结果: {result}")
  27. except Exception as e:
  28. print(f"测试失败: {e}")
  29. finally:
  30. driver.quit()

7.2 运行测试

  • 启动 Appium 服务器
  • 启动 Android 模拟器或连接 Android 设备
  • 执行脚本:
    1. - bash
    2. - python test\_calculator.py

8. 常见问题解决

  • Appium 服务器无法启动:
    • 检查端口 4723 是否被占用(lsof -i:4723)
    • 尝试以管理员 /root 权限启动
  • 连接设备失败:
    • Android:确保adb devices能识别到设备
    • iOS:确保 Xcode 已信任开发者证书
  • 元素定位失败:
    • 使用 Appium Inspector 辅助定位
    • 检查应用包名和 Activity 名称是否正确

9. iOS 测试额外配置

若需测试 iOS 应用,还需:

  • 安装 WebDriverAgent

    1. bash
    2. appium driver install xcuitest
  • 配置 Xcode 开发者证书(需 Apple ID)

  • 在 Appium Desired Capabilities 中添加:

    1. python 运行
    2. "xcodeOrgId": "YOUR\_TEAM\_ID", # 开发者团队ID
    3. "xcodeSigningId": "iPhone Developer"

三、Appium 定位元素的方法

1. ID 定位(推荐)

通过元素的resource-id(Android)或name/id(iOS)定位。

  1. python 运行
  2. \# Android示例
  3. element = driver.find\_element('id', 'com.example.app:id/button\_login')
  4. \# iOS示例
  5. element = driver.find\_element('id', 'LoginButton')

2. XPath 定位(灵活)

通过元素路径和属性定位,支持复杂查询。

  1. python 运行
  2. \# 按文本查找
  3. element = driver.find\_element('xpath', '//android.widget.TextView\[@text="登录"\]')
  4. \# 按索引查找(不推荐,易变)
  5. element = driver.find\_element('xpath', '(//android.widget.Button)\[2\]')
  6. \# 组合条件
  7. element = driver.find\_element('xpath', '//android.widget.EditText\[@hint="请输入用户名"\]')

3. 类名定位

通过元素的类名(如android.widget.Button)定位,适用于批量操作。

  1. python 运行
  2. \# 获取所有按钮
  3. buttons = driver.find\_elements('class name', 'android.widget.Button')

4. 内容描述(Accessibility ID)

通过元素的content-desc属性定位,推荐用于自动化测试。

  1. python 运行
  2. element = driver.find\_element('accessibility id', 'LoginButton')

5. Android 专用:UI Automator 定位

使用 Android 的 UiAutomator 框架表达式。

  1. python 运行
  2. \# 按文本包含关系查找
  3. element = driver.find\_element('android uiautomator', 'new UiSelector().textContains("请输入")')
  4. \# 按类名和索引查找
  5. element = driver.find\_element('android uiautomator', 'new UiSelector().className("android.widget.EditText").index(0)')

6. iOS 专用:XCUITest 定位

使用 iOS 的 XCUITest 框架表达式。

  1. python 运行
  2. \# 按标签名和文本查找
  3. element = driver.find\_element('ios predicate string', 'type == "XCUIElementTypeButton" AND name == "登录"')
  4. \# 按父子关系查找
  5. element = driver.find\_element('ios predicate string', 'parent.type == "XCUIElementTypeTable" AND label ==

7. CSS 选择器(WebView)

在混合应用的 WebView 上下文中使用 CSS 选择器。

  1. python运行
  2. \# 切换到WebView上下文
  3. webview\_context = \[ctx for ctx in driver.contexts if 'WEBVIEW' in ctx\]\[0\]
  4. driver.switch\_to.context(webview\_context)
  5. \# 使用CSS选择器定位
  6. element = driver.find\_element('css selector', 'button.login')

8. 链接文本(WebView)

在 WebView 中通过链接文本定位。

  1. python 运行
  2. element = driver.find\_element('link text', '注册')
  3. element = driver.find\_element('partial link text', '忘记密码')

四、Appium 进阶功能

1. 复杂手势操作

Appium 支持模拟各种触摸手势,如滑动、长按、捏合等。

1.1 TouchAction 类(低级 API)

  1. python 运行
  2. from appium.webdriver.common.touch\_action import TouchAction
  3. \# 长按操作
  4. action = TouchAction(driver)
  5. action.press(x=100, y=200).wait(2000).release().perform() # 长按2秒
  6. \# 滑动操作
  7. action.press(x=100, y=500).move\_to(x=100, y=100).release().perform() # 向上滑动

1.2 多点触控(MultiAction)

  1. python 运行
  2. from appium.webdriver.common.touch\_action import TouchAction
  3. from appium.webdriver.common.multi\_action import MultiAction
  4. \# 捏合缩放(模拟双指操作)
  5. action1 = TouchAction(driver).press(x=100, y=200).move\_to(x=150, y=250).release()
  6. action2 = TouchAction(driver).press(x=300, y=400).move\_to(x=250, y=350).release()
  7. MultiAction(driver).add(action1, action2).perform()

1.3 iOS 特定手势

  1. python 运行
  2. \# iOS 轻扫操作
  3. driver.execute\_script("mobile: swipe", {"direction": "left", "element": element\_id})
  4. \# iOS 双指点击
  5. driver.execute\_script("mobile: doubleTap", {"element": element\_id})

2. 上下文切换(WebView 和原生界面)

测试混合应用时,需要在原生界面和 WebView 之间切换。

  1. python 运行
  2. \# 获取所有上下文
  3. contexts = driver.contexts
  4. print(contexts) # 输出类似: \['NATIVE\_APP', 'WEBVIEW\_com.example.app'\]
  5. \# 切换到 WebView
  6. driver.switch\_to.context('WEBVIEW\_com.example.app')
  7. \# WebView 中使用 Web 定位方式
  8. driver.find\_element('css selector', 'button.login').click()
  9. \# 切回原生界面
  10. driver.switch\_to.context('NATIVE\_APP')

3. Appium 与 CI/CD 集成

将 Appium 测试接入持续集成流程,实现自动化部署和测试。

3.1 Jenkins 集成示例

  1. groovy
  2. pipeline {
  3. agent any
  4. stages {
  5. stage('Install Dependencies') {
  6. steps {
  7. sh 'npm install -g appium'
  8. sh 'pip install Appium-Python-Client'
  9. }
  10. }
  11. stage('Run Tests') {
  12. steps {
  13. sh 'appium &' # 后台启动 Appium 服务器
  14. sh 'python -m pytest tests/' # 执行测试
  15. }
  16. }
  17. }
  18. }

3.2 GitHub Actions 配置

  1. yaml
  2. name: Appium Tests
  3. on: \[push\]
  4. jobs:
  5. test:
  6. runs-on: macos-latest # 或 ubuntu-latest
  7. steps:
  8. - uses: actions/checkout@v3
  9. - name: Setup Python
  10. uses: actions/setup-python@v4
  11. with:
  12. python-version: 3.9
  13. - name: Install Appium
  14. run: |
  15. npm install -g appium
  16. appium driver install uiautomator2
  17. - name: Install Dependencies
  18. run: pip install Appium-Python-Client pytest
  19. - name: Start Appium Server
  20. run: appium &
  21. - name: Run Tests
  22. run: pytest tests/

4. 并行测试(多设备同时执行)

通过 Appium Grid 或自定义脚本实现多设备并行测试,提高效率。

4.1 Appium Grid 配置

  1. bash
  2. \# 启动 Selenium Grid 服务器
  3. java -jar selenium-server-standalone-4.8.0.jar standalone
  4. \# 注册 Appium 节点到 Grid
  5. appium --nodeconfig nodeconfig.json

nodeconfig.json 示例: json { “capabilities”: [ { “browserName”: “Android”, “platform”: “ANDROID”, “deviceName”: “emulator-5554” }, { “browserName”: “iOS”, “platform”: “IOS”, “deviceName”: “iPhone SE” } ], “configuration”: { “proxy”: “org.openqa.grid.selenium.proxy.DefaultRemoteProxy”, “maxSession”: 1, “port”: 4723, “host”: “localhost”, “register”: true, “registerCycle”: 5000, “hubPort”: 4444, “hubHost”: “localhost” } }

4.2 Python 并行测试示例

  1. python 运行
  2. import pytest
  3. from appium import webdriver
  4. @pytest.fixture(params=\["device1", "device2"\])
  5. def driver(request):
  6. \# 根据设备参数配置不同的 Desired Capabilities
  7. caps = {
  8. "device1": {
  9. "platformName": "Android",
  10. "deviceName": "emulator-5554",
  11. "app": "/path/to/app1.apk"
  12. },
  13. "device2": {
  14. "platformName": "Android",
  15. "deviceName": "emulator-5556",
  16. "app": "/path/to/app2.apk"
  17. }
  18. }
  19. driver = webdriver.Remote('http://localhost:4723/wd/hub', caps\[request.param\])
  20. yield driver
  21. driver.quit()
  22. def test\_example(driver):
  23. \# 测试用例,会在每个设备上执行
  24. driver.find\_element('id', 'button').click()

5. 性能监控与分析

通过 Appium 监控应用的性能指标,如 CPU、内存、网络流量等。

5.1 Android 性能监控

  1. python 运行
  2. \# 获取 CPU 使用率
  3. cpu\_usage = driver.execute\_script('mobile: getPerformanceData', {
  4. 'packageName': 'com.example.app',
  5. 'dataType': 'cpuInfo',
  6. 'timePeriod': 10000
  7. })
  8. \# 获取内存使用
  9. memory\_info = driver.execute\_script('mobile: getPerformanceData', {
  10. 'packageName': 'com.example.app',
  11. 'dataType': 'memoryInfo'
  12. })

5.2 iOS 性能监控

  1. python 运行
  2. \# 获取 iOS 应用性能数据
  3. performance\_data = driver.execute\_script('mobile: getPerformanceData', {
  4. 'processName': 'com.example.app',
  5. 'performanceDataType': 'cpuUsage'
  6. })

6. 自定义 Appium 命令

通过扩展 Appium 服务器插件,实现自定义功能。

6.1 创建自定义命令(Node.js 示例)

  1. javascript
  2. // 自定义插件:添加屏幕录制功能
  3. class ScreenRecorderPlugin {
  4. static newMethodMap = {
  5. '/session/:sessionId/startRecording': {
  6. POST: {command: 'startRecordingScreen'}
  7. },
  8. '/session/:sessionId/stopRecording': {
  9. POST: {command: 'stopRecordingScreen'}
  10. }
  11. }
  12. async startRecordingScreen() {
  13. // 实现屏幕录制启动逻辑
  14. return await this.adb.startScreenRecording();
  15. }
  16. async stopRecordingScreen() {
  17. // 实现屏幕录制停止逻辑
  18. return await this.adb.stopScreenRecording();
  19. }
  20. }
  21. // 注册插件
  22. module.exports = {
  23. plugins: {
  24. screenRecorder: ScreenRecorderPlugin
  25. }
  26. };

6.2 在 Python 中使用自定义命令

  1. python运行
  2. \# 启动录制
  3. driver.execute\_script('mobile: startRecordingScreen')
  4. \# 执行测试操作
  5. driver.find\_element('id', 'button').click()
  6. \# 停止录制并保存视频
  7. video\_data = driver.execute\_script('mobile: stopRecordingScreen')
  8. with open('recording.mp4', 'wb') as f:
  9. f.write(base64.b64decode(video\_data))

7. 处理特殊场景

7.1 权限弹窗处理

  1. python 运行
  2. \# Android 权限弹窗处理
  3. try:
  4. allow\_button = WebDriverWait(driver, 5).until(
  5. EC.element\_to\_be\_clickable(('id','com.android.packageinstaller:id/permission\_allow\_button'))
  6. )
  7. allow\_button.click()
  8. except:
  9. pass # 无权限弹窗则忽略

7.2 推送通知处理

  1. python 运行
  2. \# iOS 推送通知允许按钮
  3. try:
  4. alert = WebDriverWait(driver, 5).until(EC.alert\_is\_present())
  5. driver.switch\_to.alert.accept() # 接受通知
  6. except:
  7. pass

7.3 键盘操作

  1. pytho 运行
  2. \# 隐藏键盘
  3. driver.hide\_keyboard()
  4. \# 直接输入文本(不使用键盘)
  5. driver.set\_value(element, "直接输入文本")

8. Appium 与其他工具集成

8.1与 Allure 集成生成美观测试报告

  1. bash
  2. pip install allure-pytest
  3. pytest --alluredir=./results
  4. allure serve ./results

8.2与 Applitools 集成实现视觉测试

  1. python 运行
  2. from applitools.selenium import Eyes
  3. eyes = Eyes()
  4. eyes.api\_key = 'YOUR\_API\_KEY'
  5. try:
  6. eyes.open(driver, "App Name", "Test Name")
  7. eyes.check\_window("Main Screen")
  8. finally:
  9. eyes.close()