All Products
Search
Document Center

Mobile Testing:Write an Android test script

Last Updated:Jul 10, 2023

Mobile Testing supports automated testing code that is written based on Appium.

Important

Mobile Testing supports third-party libraries, such as pytest, unittest, and Robot Framework. If you want to use another framework, contact technical support.

Prerequisites

  • You are familiar with how to use Appium for automated testing. For more information, see Appium documentation.

  • You have basic Python programming skills.

Background information

To write an Android test script, you must perform the following operations:

Step 1: Create a Capabilities file

Write a Capabilities file named desired_capabilities.py in the Python language and store the file in the root directory.

Important

desired_capabilities.py is used to specify the test environment only when the test script is executed locally.

The desired_capabilities.py file contains the get_uri() and get_desired_capabilities() functions.

Function

Description

get_desired_capabilities()

Queries the parameters of the current session.

You can configure the parameters based on your business requirements. For more information, see Appium Desired Capabilities.

get_uri()

Returns the URL of the Appium server.

Sample code

#!/usr/bin/env python

def get_desired_capabilities():
    desired_caps = {
        'platformName': 'Android',
        'platformVersion': '7.0',
        'deviceName': 'V889F',
        'appPackage': 'com.alibaba.mts.mtsdemoapp',
        'appWaitPackage': 'com.example.Android.myapp',
        'app': 'D:/home/xx/xx/xx/xx.apk',
        'newCommandTimeout': 30,
        'automationName': 'Appium'
    }
    return desired_caps

def get_uri():
    return "http://localhost:50000/wd/hub"

Parameter description

  • The following table describes the parameters that are configured in the get_desired_capabilities() function.

Parameter

Description

platformName

The system type of the test device. Valid values: Android and iOS.

platformVersion

The system version of the test device.

deviceName

The name of the test device.

appPackage

The package name of the app that you want to test. This parameter is valid only in the Android system.

appWaitPackage

The package name of the app that is waiting to be started during the test. This parameter is valid only in the Android system.

app

The storage path of the app installation file.

newCommandTimeout

The maximum time interval allowed between two commands. Unit: seconds.

If the time interval between two commands exceeds the specified value, the Appium server ends the current session.

automationName

The name of the automation engine used in the current session.

  • If the system version of the device is earlier than Android 4.2, set the value to Selendroid.

  • If the system version of the device is iOS 4.2 or Android 4.2 or later, set the value to Appium.

  • By default, the listener port of the on-premises Appium server is set to 50000. In this case, the return value of get_uri() is http://localhost:50000/wd/hub.

Step 2: Write a test script

Write a test script named main.py in the Python language and store the script in the root directory. The script is used as an entry to perform automated testing.

Note

Mobile Testing implements functional testing by executing the main.py test script.

Sample code and description:

# -*- coding: utf-8 -*-

from appium import webdriver

# Import the desired_capabilities.py file that was created in the root directory.
import desired_capabilities

# Use unittest of Python as the unit testing tool.
from unittest import TestCase

# Use unittest of Python as the unit testing tool.
import unittest

# Use the time.sleep(xx) function to suspend the execution of the current thread for a specific number of seconds.
import time

class MqcTest(TestCase):

   global automationName

   def setUp(self):
       # Query the specified capabilities and notify the Appium server to create the corresponding session. 
       desired_caps = desired_capabilities.get_desired_capabilities()
       # Query the URL of the Appium server. 
       uri = desired_capabilities.get_uri()
       # Query the testing framework that is used.
       self.automationName = desired_caps.get('automationName')
       # Create a session and query the driver object that encapsulates all device operations. 
       self.driver = webdriver.Remote(uri, desired_caps)

   def test_searchbox(self):
        # Find the control that contains the "Tab4" string. 
        if self.automationName == 'Appium':
            tab4 = self.driver.find_element_by_name("Tab4")
        else:
            tab4 = self.driver.find_element_by_link_text("Tab4")
        # Click the control that contains the "Tab4" string.
        tab4.click()

        # Wait 2 seconds.
        time.sleep(2)

        # Find the username and password fields by control class name. 
        editTexts = self.driver.find_elements_by_class_name("android.widget.EditText")
        # Enter the username and the password. [0] specifies the username and [1] specifies the password.
        editTexts[0].send_keys("admin")
        editTexts[1].send_keys("admin")
        # Hide the soft keyboard that appears.
        self.driver.hide_keyboard()

        # Find and then click the Log On button.
        if self.automationName == 'Appium':
            self.driver.find_element_by_name("Log On").click()
        else:
            self.driver.find_element_by_link_text("Log On").click()
        # Wait 3 seconds for the logon process to complete.  
        time.sleep(3)

   def tearDown(self): 
        # The test is complete. Exit the session.  
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

Step 3: Start the Appium server

Run the appium command on the CLI to start the Appium server. Example: appium -p 50000.

Parameters

Parameter

Description

-p

Specifies the listener port of the Appium server.

-a

Specifies the IP address of the Appium server.

--selendroid-port

Specifies the port of Android Debug Bridge (adb) in Selendroid mode.

-U

Specifies the serial number of the test device when multiple devices are connected to the Appium server.

--full-reset

Specifies to clean up the device after the test case is executed.

Step 4: Verify the test script

  1. Connect a mobile phone to your computer.

    • Connect a mobile phone for which the developer mode is enabled to your computer.

    • Connect to a remote device, run the adb connect command, and then connect the remote device to your computer.

  2. Run the python main.py command on the CLI to execute and verify the main.py test script.

Step 5: Upload the test script to the Mobile Testing console

  1. Compress the main.py file into a ZIP file in the root directory.

  2. In the Mobile Testing console, create a script by uploading the main.py file. The script is used for subsequent functional testing on Android devices.

    For more information about how to create a script, see Create a script.