如何用 Appium 测试移动应用中的手机验证

· 5 分钟阅读 · QuickInbox 团队

  • Appium
  • 移动端
  • 短信

移动应用常常以“输入你的手机号码”开始。在模拟器或设备云上,没有 SIM 卡来接收验证码。一个能通过 API 读取的测试号码就能解决这个问题。

为什么不用设备自己的号码?

模拟器没有手机号码。设备云里的真机是共享的,你的测试读不到它们的短信。即使能读,把测试绑在一部实体手机上也很脆弱。云端测试号码在任何设备上都一样可用。

第 1 步:辅助函数

# sms.py - read texts sent to your QuickInbox test number
import os, re, time, requests

BASE = "https://business.quickinbox.net"
HEADERS = {"X-API-Key": os.environ["QI_KEY"]}

def get_number():
    numbers = requests.get(f"{BASE}/api/business/sms/numbers", headers=HEADERS).json()["numbers"]
    return numbers[0]  # {"id": ..., "phone_number": "+1...", ...}

def list_messages(number_id):
    r = requests.get(f"{BASE}/api/business/sms/numbers/{number_id}/messages", headers=HEADERS)
    r.raise_for_status()
    return r.json()["messages"]  # newest first

def snapshot(number_id):
    return {m["id"] for m in list_messages(number_id)}

def wait_for_code(number_id, seen, timeout=90, pattern=r"\b(\d{4,8})\b"):
    deadline = time.time() + timeout
    while time.time() < deadline:
        for m in list_messages(number_id):
            if m["id"] not in seen and re.search(pattern, m["body"]):
                return re.search(pattern, m["body"]).group(1)
        time.sleep(3)
    raise TimeoutError("No new SMS code arrived in time")

第 2 步:Appium 测试(Python)

# test_onboarding.py
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
import sms

def test_phone_onboarding():
    number = sms.get_number()
    seen = sms.snapshot(number["id"])

    opts = UiAutomator2Options()
    opts.app = "/path/to/app-debug.apk"
    driver = webdriver.Remote("http://127.0.0.1:4723", options=opts)
    try:
        local = number["phone_number"].removeprefix("+1")
        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "phone-input").send_keys(local)
        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "send-code").click()

        code = sms.wait_for_code(number["id"], seen)
        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "code-input").send_keys(code)
        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "verify").click()
        assert driver.find_element(AppiumBy.ACCESSIBILITY_ID, "home-screen")
    finally:
        driver.quit()

iOS 改用 XCUITestOptions,短信部分保持不变。

移动端小技巧

  • 自动填充:iOS 和 Android 会从设备自己的短信中建议验证码。这里不会发生,所以要测手动输入的路径,这也是所有用户都能用的后备方式。
  • 国家选择器:号码是美国号码,所以按你的应用要求选择 +1,或输入不带国家代码的号码。
  • 无障碍 id:给输入框设置稳定的 id,比用文字选择器稳定得多。

相关指南

获取测试号码:每个 QuickInbox 付费套餐都包含一个真实的美国手机号码和每月短信额度,套餐每月 $9 起。额外短信包每月 $5 起。参见短信测试和价格。

← 全部文章