首页 > 解决方案 > 将 Appium 驱动程序实例从一个类传递到另一个类

问题描述

我正在自动化一个android应用程序,并在设置类文件中有功能方法,并从该方法返回驱动程序实例。

我的一个页面有一个类文件,我在其中调用该功能方法并使用驱动程序实例来定位元素,尽管我无法在其他类文件中使用该驱动程序实例。这样做的最佳方法是什么?

标签: appiumappium-android

解决方案


这应该使用 OOP 来完成。您应该定义一个用于创建驱动程序实例的主类,并定义在其中创建一个驱动程序实例。然后从主类继承其他类。假设我们调用它MainClass。然后我们应该自动化我们应用程序的两个部分,例如RegisterLogin。它应该像这样实现:(Python)

主类.py

from appium import webdriver


class MainClass:
    def __init__(self):
        self.driver_instance = None

    def open_application(self, udid=None):
        caps = {
            'platformName': 'Android', 'deviceName': Galaxy A7, 'automationName': 'UiAutomator2',
            'skipServerInstallation': True, 'appActivity': 'YOUR_APP_START_ACTIVITY', 'noReset': no_reset,
            'udid': udid, 'newCommandTimeout': 1200, 'autoGrantPermissions': True,
            'appPackage': 'YOUR_APP_PACKAGE_NAME'}
        driver = webdriver.Remote(str(appium_server), caps)
        self.driver_instance = driver
        return driver

我的应用程序.py

from MainClass import MainClass


class MyApplication(MainClass)
        def __init__(self):
        super().__init__()

    def open_my_application(udid=None):
        self.open_application()

验证.py

from MainClass import MainClass


class Authenticate(MainClass)
        def __init__(self):
        super().__init__()

    def login(self, username, password):
        self.driver_instance.find_element_by_xpath("//input[1]").set_text(username)
        self.driver_instance.find_element_by_xpath("//input[2]").set_text(password)
        self.driver_instance.find_element_by_xpath("//button[text='Submit']").click()

    def register(self, username, password, name, phone):
        self.driver_instance.find_element_by_xpath("//input[1]").set_text(username)
        self.driver_instance.find_element_by_xpath("//input[2]").set_text(password)
        self.driver_instance.find_element_by_xpath("//input[3]").set_text(name)
        self.driver_instance.find_element_by_xpath("//input[4]").set_text(phone)
        

测试.py

import MyApplication
import Authenticate

MyApplication().open_my_application(udid="5c1425bd54c88")
Authenticate().login('user12', 'user12-password')

1-正如您在上面的示例中看到的,首先我们创建MainClass并包含我们open_application()在这里调用的创建驱动程序实例关键字,它将创建实例并将驱动程序实例变量存储为self.driver_instance变量。

2-然后我们创建另一个名为的类,该类MyApplication继承自MainClass. 然后我们定义一个调用的函数open_my_application(),它将调用open_application()fromMainClass作为实例(类对象)。因此,self.driver_instance将存储为MainClass's 变量,您可以根据需要创建任何继承自MainClass的类。

3-我们创建一个名为Authenticate登录和注册的类。

4- Test.py 最后是一个示例测试文件。

希望这可以帮助。


推荐阅读