1. 程式人生 > 其它 >Android Hybrid (混合頁面)自動化測試

Android Hybrid (混合頁面)自動化測試

定義

個人理解:原生app中嵌入了H5頁面

前提條件

  • PC端
    • 瀏覽器可訪問:https://www.google.com/
    • 下載與app對應版本的chromedriver
  • 手機端
    • 應用程式碼需要開啟webview開關
    • 如果是線上,需要開發配合留後門,或者定義個其他欄位
  • 程式碼
    • 需要appPackage、appActivity資訊
    • desirecapability中新增"chromedriverExecutable"配置項,指定chromedriver的執行路徑

元素定位

  • 通過uiautomatorviewer渲染後的頁面進行定位:該方法不確定性較大,換個機器可能就不適用,一般不建議使用這個方法。
  • 用瀏覽器通過inspect除錯視窗定位:該方式正規可靠,推薦使用該方法。

處理上下文

  • 獲取當前所有的context:context_list=driver.contexts
  • 從native切換到webview:driver.switch_to.context(context_list[-1])
  • 然後如果後續還要操作native頁面,還需要切換回native:driver.switch_to.context(context_list[0])或者driver.switch_to.context("Native_APP")

個人Demo

#!/usr/bin/python3.8.9
# -*- coding: utf-8 -*-

from time import sleep

# @Author  : Tina Yu
# @Time    : 2021-12-14 15:37
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy


class TestWebviewHybridDemo:

    def setup(self):
        desire_cap = {
            "platformName": "Android",
            "deviceName": "127.0.0.1:7555",
            "appPackage": "io.appium.android.apis",
            "appActivity": ".ApiDemos",
            "noReset": True,
            "chromedriverExecutable": "D:/BrowserDriver/chromedriver_win32_2.39/chromedriver.exe"
        }
        self.driver = webdriver.Remote("http://localhost:4723/wd/hub", desire_cap)
        self.driver.implicitly_wait(10)

    def teardown(self):
        self.driver.quit()

    def test_hybrid_webview(self):
        self.driver.find_element(MobileBy.ACCESSIBILITY_ID, "Views").click()
        text_view = "WebView"
        self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,
                                 'new UiScrollable(new UiSelector().scrollable(true))'
                                 f'.scrollIntoView(new UiSelector().text("{text_view}"));').click()
        # 通過uiautomator定位WebView元素:原理是工具獲取到資訊後渲染到工具頁面上,一些渲染是不準確的,所以不建議。
        # self.driver.find_element(MobileBy.XPATH, "//*[@text='i has no focus']").send_keys("這是測試字串!")
        # self.driver.find_element(MobileBy.XPATH, "//*[@text='i am a link']").click()

        # 獲取contexts
        print(self.driver.contexts)

        # 切換上下文,從native切換到WebView,類似於selenium切換iframe
        self.driver.switch_to.context(self.driver.contexts[-1])

        # 通過瀏覽器的inspect除錯工具定位WebView元素,正規可靠
        self.driver.find_element(MobileBy.ID, "i_am_a_textbox").send_keys("Test string!")
        self.driver.find_element(MobileBy.ID, "i am a link").click()

        # 操作完WebView之後還要繼續操作原生頁面,則需要切換回native
        self.driver.switch_to.context(self.driver.contexts[0])  # 方式一
        # self.driver.switch_to.context("Native_APP")  # 方式二、Native_APP是固定引數

        sleep(3)

更好的參考資料:https://www.cnblogs.com/123blog/p/12624015.html

本文來自部落格園,作者:于慧妃,轉載請註明原文連結:https://www.cnblogs.com/fengyudeleishui/p/15688953.html