Appium do android function automation test

Source: Internet
Author: User
Tags try catch appium

Objective

Android has more than 2 years of automation capabilities, the use of functional automation framework has robotium, Uiautomator, Appium. Recently, research the automation case reuse scheme, researched the automation framework of appium, and applied it to the standard of Bank one account, this article introduces the Android function Automation combat experience based on appium in detail. The main contents include the following aspects:

    • Appium Framework Principle Introduction
    • Appium Framework Common API Introduction
    • Construction of automated development environment based on Appium framework
    • Automatic case development and layered structure design
    • Automated test case writing specifications and precautions
    • Functional Automation Access Continuous integration solution
Android Common function Automation Framework comparison

The following table gives a comparison of three frameworks for Robotium, Uiautomator, and Appium.
It is particularly important to understand the characteristics of each automation framework and to choose a suitable framework in combination with the product's own characteristics.


Appium Framework Principle Introduction

Appium is an open-source, cross-platform, automated testing tool for testing native and lightweight mobile applications that support iOS, Android and Firefoxos platforms. Appium drives Apple's UIAutomation library and Android's uiautomator framework, using Selenium's Webdriver JSON protocol. Is appium on the Android side of the schematic diagram



As can be seen, Appium client is a Webdriver native API of some extension and encapsulation, it with the native Webdriver to use, both indispensable. Appium server has two main functions: first it acts as an HTTP server, receiving commands sent from the Appium client (which can be considered a specific action in case). Second, it acts as a bootstrap client, after receiving the command of the client, through the socket, sends these commands to the target Android Machine's bootstrap to drive the Uiautomator to perform the automation operation. About the working principle of appium, many online materials, no longer detailed introduction, can refer to the following links
Http://www.2cto.com/kf/201410/347851.html
Http://www.blogjava.net/qileilove/archive/2014/12/23/421659.html

Appium Framework Common API Introduction

The Appium API is included in the Appium client, and the following table gives the client for the different language platforms


The following table shows the common API for the Java platform, and other APIs can be self-Baidu or view the client source code



Appium element Positioning and operation of the API is separate, this is different from the Robotium framework, and Google's new iOS-enabled feature Automation framework Earlgrey is similar. The API for element positioning needs to be noted: When the element is successfully positioned, the Webelement object is returned, but if the element cannot be located, the API will direct an error instead of returning null. This is often error-prone for common operations such as "Judging whether a control is present", such as using the following code to determine whether a login button exists.

public boolean isLoginButtonShow(){ WebElement wl = DriverManager.getInstance().findElementById(packagename + ":id/login_input_account"); return wl.isDisplayed(); }

Returns True when the login button is present, but the above code does not return FALSE if the login button does not exist, but crashes directly on line 2nd. Exceptions can be caught by a try catch, modified as follows:

public boolean isLoginButtonShow(){ try{ WebElement wl = DriverManager.getInstance().findElementById(packagename + ":id/login_input_account"); return wl.isDisplayed(); }catch (Exception e){ return false; } }
Construction of automated development environment based on Appium framework

The beginning of everything is difficult, the building of automation development environment will be more troublesome. Here's a detailed explanation of how to build an automated, appium-based development environment under the Mac OS operating system.
1, Android Development Environment Construction (JDK/SDK/ANDROIDSTUDIO) Please Baidu, the required installation package can be downloaded in the following pages:
http://tools.android-studio.org
Appium for Mac installation can refer to the following connections:
Http://www.cnblogs.com/oscarxie/p/3894559.html
where Appium installation, it is recommended to use DMG installation, click Download installation package. "NPM install-g appium" command line installation pro-Test has been error, FQ also error.
2, Androidstudio in the new Android project Appdemo.
3. Create Java Module (appium): new->new Module->java Library, this Java project is used to develop automation case.
4. Install Appium Client: Create Java Module (selenium), import related selenium package in libs directory, click Download Selenium compress Package
5, Appium module Add Selenium dependency: File->project structure->modelues Select appium->dependencies Add Selenium module.
6, Appium module, new Java class, began to develop automation case. The Appdemo project directory structure is as follows:


7. Start appium Server (command line or graphical interface), note that the no reset option is checked in Android settings at startup to prevent the app from being reinstalled every time the case is executed, as shown below.



8, case execution, can be executed by the IDE and script two ways
IDE Mode: Case name right-click->run
Script mode: auto_run.sh, see below

#!/bin/bash  #auto_run. Shsource ~/.bash_profile CD./appdemogradle cleangradle buildexport CLASSPATH= $APPIUM _home/java-client-3.3.0.jar: $APPIUM _home/ Selenium-java-2.48.2-srcs.jar: $APPIUM _home/selenium-java-2.48.2.jar: $APPIUM _home/junit-4.12.jar: $APPIUM _home/hamcrest-core-1.3.jar:< Span class= "hljs-variable" > $APPIUM _home/libs/* CD./appiumjava-classpath  $CLASSPATH:./build/libs/appium.jar org.junit.runner.JUnitCore Com.incito.appiumdemo.cases.PersonalCente           

Where classpath needs to be set to the Appium client path,
Com.incito.appiumdemo.cases.PersonalCenter is the class of case where the script is executed in a way that facilitates continuous integration and platform of automation access.
This completes the automated development environment based on the Appium, and the next section describes how to develop a hierarchical design of automated cases and case.

Automatic case development and case hierarchical structure design based on Appium

First, create a common base class appiumtestbase for each case, containing the setup and teardown two methods, each of which inherits from the base class at a later time. The code is as follows:

PublicClassAppiumtestbase {Public webdriverwait webwait;Private Androiddriver driver;@BeforePublicvoidSetUp()Throws Exception {File Classpathroot =New File (System.getproperty ("User.dir")); File Appdir =New File (Classpathroot,"Apps"); File app =New File (Appdir, Config.current_bank); Desiredcapabilities capabilities =New Desiredcapabilities (); Capabilities.setcapability ("DeviceName", config.device_name); Capabilities.setcapability (Capabilitytype.browser_name,""); Capabilities.setcapability (Capabilitytype.version,"5.0.1"); Capabilities.setcapability ("PlatformName","Android"); Capabilities.setcapability ("App", App.getabsolutepath ()); Capabilities.setcapability ( "Udid", config.device_name); //ADB devices obtained value Driver = new androiddriver (new URL (" http://127.0.0.1: "+config.appium_port+  "/wd/hub"), capabilities); webwait = new webdriverwait (Driver,10); Drivermanager.init (driver); Drivermanager.initwebwait (webwait); driver.manage (). Timeouts (). implicitlywait ( 10, timeunit.seconds);  }  @After public void teardown ()  Throws Exception {driver.quit ();}             

The setup operation consists of importing the app to be tested APK package, setting the parameters required to connect with the Appium server, and initializing the Androiddriver object. For example, to sign in case, it needs to inherit Appiumtestbase, the code is as follows:

Package Com.incito.appiumdemo;Import Org.junit.After;Import Org.junit.Before;Import Org.openqa.selenium.remote.CapabilityType;Import org.openqa.selenium.remote.DesiredCapabilities;Import org.openqa.selenium.support.ui.WebDriverWait;Import Java.io.File;Import Java.net.URL;Import Java.util.concurrent.TimeUnit;Import Io.appium.java_client.android.AndroidDriver;PublicClassAccountLoginExtendsappiumtestbase{/** * Case Number ACCOUNTLOGIN_001 * * * * * * * * @throws ****exception */ @Test public void testaccountlogin () throws Exception {account.*getinstance* (). Gotologinpage (); Account.*getinstance* (). Dologin (); }/** * Case Number accountlogin_002 * **** @throws ****exception */ Span class= "Hljs-meta" > @Test public void testloginout () throws Exception {account.*getinstance* (). Gotogestureloginpage (); Account.*getinstance* (). Dogesturelogin (config.*current_username*); Personal.*getinstance* (). Dologout (); } 

In Testaccountlogin case, two steps were taken: Enter the login page and perform a login operation. Both of these steps are encapsulated within the account class. This introduces a layered design framework for automated case, such as:


Paste_image.png

One of the frequently encountered problems in the automation development process is that as the product is continually updated, the UI of the app changes constantly, how automation can cope with such changes, and how to reduce its maintenance costs. Case layered design is mainly based on the consideration of automatic maintainability, maintainability is one of the most important evaluation indexes of function automation, which directly determines whether automation can proceed. If the number of case to a certain extent, if not the packaging, layered design ideas, it is very likely to appear "reaching" problem. is a hierarchical catalog diagram of the standard automation case.

The following is an example of a login case to learn more about its hierarchical invocation relationship. Login case in the cases layer of the AccountLogin class, its code has been shown above, back to Testaccountlogin case operation, the second operation is Account.getinstance (). Dologin (); The sign-in operation is performed on the login page, which is encapsulated in the account class of the business layer, and the code snippet is as follows:
public void doLogin(){ LoginUiAction.*getInstance*().enterUsername(Config.*CURRENT_USERNAME*); LoginUiAction.*getInstance*().enterPassword(Config.*CURRENT_PASSWORD*); LoginUiAction.*getInstance*().clickLogin(); HomeUiAction.*getInstance*().clickOnCancelGesture(); Assert.*assertTrue*(LoginUiAction.*getInstance*().isLogin());}

The Dologin () method executes the "Enter user name, enter password, click the login button, determine whether the login is successful" operation, obviously these steps are in the UI layer Loginuiaction class. Let's check Loginuiaction.getinstance () again.
What is done in the Enterusername () method, the code snippet is as follows:

//输入用户名public void enterUsername(String username){ WebElement wl = DriverManager.*getInstance*().findElementById(packagename + ":id/login_input_account"); wl.clear(); wl.sendKeys(username);}

Enterusername () method, first locate the user name input box based on the ID, then empty the input box, and then enter the user name, which are the APIs provided in the Appium client. This demonstrates the layered invocation process for login case: Cases->business->ui->api. As long as the business logic is the same, the case maintenance task is placed primarily on the UI layer, and the upper layer does not need to be changed, which can greatly reduce the maintenance cost of the transaction.
In the Dologin () method, there is a "determine the success of the login" operation, the assertion operation is an essential part of the automated test case, the following is the introduction of automated test case writing specifications.

Automated test case writing specifications and precautions

A case generally needs to include the following elements:

    • Data preparation
    • Specific operation
    • Verification Point
    • Clear Operation Results

Data preparation refers to the preparation of test accounts, false data, etc., in accordance with the business test students provided by the text case to convert; Verification point refers to the automated operation, the UI before and after the change point, such as login, the first page will appear the user name, total assets, wealth points and other controls, these are verification points Clear operation results are mainly based on case independence considerations, as far as possible to each case is independent, so that some cases fail, and will not affect other cases, of course, this will increase the granularity of cases, cases stability will be affected, the two can be self-balanced.
Here are some considerations for case development:

    1. Element positioning
      • ID (preferred)
      • Text
      • control type
      • Coordinate
    2. UI action requires a reasonable sleep
    3. Case independence
    4. Encapsulate common operations
    5. Note and case before the procedure

element positioning has ID/text/control type/coordinate four ways, it is recommended to use IDs, because as long as a control still exists, its ID change is very small, if its location changes, case is not maintenance.
Here are a few ways to find the element ID: uiautomatorviewer/hierarchyviewer/source. Uiautomatorviewer and Hierarchyviewer tools in the Android SDK, after configuring the environment variables, directly at the command line to enter commands to open the graphical tool, hierarchyviewer need phone root, It is recommended to use Uiautomatorviewer. If the source of the application to be measured, but also through the source code to find the ID, of course, this way is more painful, but familiar with business and personal growth is beneficial, I started from the source to find the ID.
For some wonderful situation, the element ID/text/control type can not be located, the use of coordinate positioning absolutely so, but not the last resort, as far as possible, because the coordinates are lost compatibility, change a phone, case may fail to execute.
UI operation requires reasonable sleep, often due to network reasons, the UI load takes a certain amount of time, the automation process needs reasonable sleep,sleep time is short, case will fail, long and wasted time. The implicit sleep scheme was introduced in the Appium framework, adding driver.manage () to the initialization code. Timeouts (). Implicitlywait (timeunit.seconds), which means that each operation waits up to 10s.
Case independence has been described before, encapsulation and annotations are easy to understand, do not explain too much.

Functional Automation Access Continuous integration solution

Functional automation is typically used for project-focused testing, regression testing, dailybuild, etc., and it is not possible to run the case manually through the IDE, typically using Jenkins or a platform-based approach to batch case execution. Here's how to automate functionality to Jenkins.


The access to Jenkins mainly uses its timing and polling functions, so we just have to get ready to build the jar (build.sh) and execute case (execcase.sh) script, put the Excute shell module in Jenkins, and then configure the timing or polling time. Build.sh and execcase.sh may refer to the auto_run.sh described in part fourth. The specific execution process is as follows: Jenkins triggers the automation job, pulls the latest apk from the build station, copies it to the Appium module's apps directory, builds the test project, generates Appium.jar (BUILD.SH), and executes the case in bulk ( execcase.sh), the final Jenkins will output the results of automated execution, but the output is not visualized, and can be developed to generate report scripts. At this point, the whole process of functional automation development based on Appium is introduced in detail.

Appium do android function automation test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.