如何用Selenium的AndroidDriver在Andrioid模拟器上进行自动化测试

如何用SeleniumAndroidDriverAndrioid模拟器上进行自动化测试

分类: QA and Testing Mobile 2012-05-02 17:0424人阅读评论(0) 收藏 举报

How to run automation on Androidemulator

1. SetupAndroid emulator
  a. Download the Android SDK
             http://developer.android.com/sdk/index.html

 
            Note that thereis an emulator bug on Gingerbread((2.3.x) that might cause WebDriver to crash.My testing is on Ice Cream Sandwich (4.0.x)

  b. Install Android SDK:
             http://developer.android.com/sdk/installing.html

  c. Start Android SDK Manager (SDKManager.exe)
  d. Select and install Package online
  e. Start AVD Manager.exe
  f. Create an emulator

2. Installthe AndroidDriver APK by using platform-tools
   a. list divce name:
             adb devices
  b. download AndroidDriver APK:
              http://code.google.com/p/selenium/downloads/list

  c. install AndroidDriver APK
             adb -s emulator-5554 -e install -r c:\android-server-2.21.0.apk
  d. start the Android WebDriver application
             adb -semulator-5554 shell am start -a android.intent.action.MAIN -norg.openqa.selenium.android.app/.MainActivity
  e. setup the port forwarding in order to forward traffic from the hostmachine to the emulator
             adb -s emulator-5554 forward tcp:8080 tcp:8080

3. Createtest case and running:
import junit.framework.TestCase; 
 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.android.AndroidDriver; 
 
public class OneTest extends TestCase { 
 
  public void testGoogle() throws Exception { 
    WebDriver driver = new AndroidDriver(); 
     
    // And now use this to visit Google 
    driver.get("http://www.google.com
"); 
     
    // Find the text input element by its name 
    WebElement element =driver.findElement(By.name("q")); 
     
    // Enter something to search for 
    element.sendKeys("Cheese!"); 
     
    // Now submit the form. WebDriver will find the form for us fromthe element 
    element.submit(); 
     
    // Check the title of the page 
    System.out.println("Page title is: " +driver.getTitle()); 
    driver.quit(); 
  } 
}

 

 

 

 

 

Introduction

Android WebDriverallows to run automated end-to-end tests that ensure your site works correctlywhen viewed from the Android browser. Android WebDriver supports all coreWebDriver APIs, and in addition to that it supports mobile spacific and HTML5APIs. Android WebDriver models many user interactions such as finger taps,flicks, finger scrolls and long presses. It can rotate the display and interactwith HTML5 features such as local storage, session storage and applicationcache.

We try to stay asclose as possible to what the user interaction with the browser is. To do so,Android WebDriver runs the tests against a WebView (rendering component used bythe Android browser) configured like the Android browser. To interact with thepage Android WebDriver uses native touch and key events. To query the DOM, ituses the JavaScript Atoms libraries.

Supported Platforms

  • The current apk     will only work with Gingerbread (2.3.x), Honeycomb (3.x), Ice Cream     Sandwich (4.0.x) and later.
    • Note      that there is an emulator      bug on Gingerbread that might cause WebDriver to crash.
  • The     last version to support Froyo (2.2) is 2.16.    

Useful Related Links

Get Started

Install the Android SDK

Download the Android SDK, and unpackit to ~/android_sdk/. NOTE: The location of the Android SDK must exist in ../android_sdk, relative to thedirectory containing the Selenium repository.

Setup the Environment

Android WebDrivertest can run on emulators or real devices for phone and tablets.

Setup the Emulator

To create an emulator,you can use the graphicalinterface provided by the Android SDK, or the commandline. Below are instructions for using the command line.

First, let's createan Android Virtual Device (AVD):

$cd ~/android_sdk/tools/ 
$
./android create avd -nmy_android -t 12-c 100M

-n: specifies thename of the AVD.

-t: specifies theplatform target. For an exhaustive list of targets, run:

./android listtargets

Make sure the targetlevel you selected corresponds to a supported SDK platform.

-c: specifies the SDcard storage space.

When prompted"Do you wish to create a custom hardware profile [no]" enter"no".

Note: AnAndroid emulator bug prevents WebDriver from running on emulators on platforms2.3 (Gingerbread). Please refer to AndroidDriver#Supported_Platformsfor more information

Now, start theemulator. This can take a while, but take a look at the FAQ below for tips onhow to improve performance of the emulator.

$./emulator-avd my_android &

Setup the Device

Simply connect yourAndroid device through USB to your machine.

Now that we're donewith the test environment setup, let's take a look at how to write tests. Thereare two options available to you to run Android WebDriver tests:

Here is acomparaison of both approach to help you choose which one suits you best.

Android WebDriver using the remote server

Android WebDriver using the Android test  framework

Tests  can be written in any supported language binding (Java, Python, Ruby, etc.)

Tests  can only br written in Java

Runs  slower because every command makes extra RPCs (HTTP requests/responses)

Runs  fasters because the tests are on the device

Ideal  if you use the same WebDriver tests on other browsers

Ideal  if you don't use the same tests on other browsers and if you already use the  Android test framework

Using the Remote Server

This approach has aclient and a server component. The client consists of your typical Junit teststhat you can run from your favorite IDE or through the command line. The serveris an Android application that contains an HTTP server. When you run the tests,each WebDriver command will make a RESTful HTTP request to the server usingJSON according to a well definedprotocol. The remote server will delegate the request to Android WebDriver,and will then return a response.

Install the WebDriver APK

Every device oremulator has a serial ID. Run this command to get the serial ID of the device oremulator you want to use:

$~/android_sdk/platform-tools/adbdevices

Download the Androidserver from our downloadspage. To install the application do:

$./adb-s <serialId>-einstall -r  android-server.apk

Make sure you areallowing installation of application not coming from Android Market. Go toSettings -> Applications, and check "Unknown Sources".

Start the AndroidWebDriver application through the UI of the device or by running this command:

$./adb-s <serialId>shell am start -a android.intent.action.MAIN-n org.openqa.selenium.android.app/.MainActivity

You can start theapplication in debug mode, which has more verbose logs by doing:

$./adb-s <serialId>shell am start -a android.intent.action.MAIN-n org.openqa.selenium.android.app/.MainActivity-edebug true

Now we need to setupthe port forwarding in order to forward traffic from the host machine to theemulator. In a terminal type:

$./adb-s <serialId>forward tcp:8080 tcp:8080

This will make theandroid server available at http://localhost:8080/wd/hubfrom the host machine. You're now ready to run the tests. Let's take a look atsome code.

Run the Tests

import junit.framework.TestCase; 
 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.android.AndroidDriver; 
 
publicclassOneTestextendsTestCase{ 
 
 
publicvoid testGoogle()throwsException{ 
   
WebDriver driver =newAndroidDriver(); 
     
   
// And now use this to visit Google 
    driver
.get("http://www.google.com"); 
     
   
// Find the text input element by its name 
   
WebElement element =driver.findElement(By.name("q")); 
     
   
// Enter something to search for 
    element
.sendKeys("Cheese!"); 
     
   
// Now submit the form. WebDriver will find the form for us fromthe element 
    element
.submit(); 
     
   
// Check the title of the page 
   
System.out.println("Pagetitle is: "+ driver.getTitle()); 
    driver
.quit(); 
 
} 
}

To compile and runthis example you will need the selenium-java-X.zip (client side piece ofselenium). Download the selenium-java-X.zip from our download page,unzip and include all jars in your IDE project. For Eclipse, right click onproject -> Build Path -> Configure Build Path -> Libraries -> AddExternal Jars.

Using the AndroidTest Framework

This approach runsthe tests directly on the device using the Androidtest framework.

You first need todownload Android WebDriver, which is an SDK extra. Open the Android SDK managerand select: Available packages → Extras → Google → WebDriver. Once the SDKmanager has downloaded WebDriver, the jars will be under the directoryandroid_sdk/extras/google/webdriver/ . In the same directory you will also findsample code containing and Android project named "SimpleApp" and anAndroid test project called "TestAnAndroidWebApp".

The SimpleAppproject, contains an activity with no layout:

publicclassSimpleAppActivityextendsActivity{ 
   
@Override 
   
publicvoid onCreate(BundlesavedInstanceState){ 
       
super.onCreate(savedInstanceState); 
   
} 
}

The reason theactivity does not have any layout is because Android WebDriver will create theWebView and automatically set the layout in that activity.

TheTestAnAndroidWebApp is an Android test project which contains a simple testthat open www.google.com, makes a search and validates that the result page'stitle contains the word "Google". Let's take a look at the code.

We instantiate thedriver by passing the activity in which the WebView will run.

WebDriver driver =newAndroidWebDriver(getActivity());

Then we use thedriver in a test to drive the web application.

    publicvoidtestGoogleWorks(){ 
       
// Loads www.google.com 
        driver
.get("http://www.google.com"); 
       
// Lookup the search box on thepage by it's HTML name property 
       
WebElement searchBox =driver.findElement(By.name("q")); 
       
// Enter keys in the search box 
        searchBox
.sendKeys("AndroidRocks!"); 
       
// Hit enter 
        searchBox
.submit(); 
       
// Ensure the title contains"Google" 
        assertTrue
(driver.getTitle().contains("Google")); 
       
// Ensure that there is at leastone link with the keyword "Android" 
        assertTrue
(driver.findElements(By.partialLinkText("Android")).size()>1); 
   
}

Here a are someinstructions to help you setup you project.

Configuring from anEclipse Project

If you are usingEclipse, first make sure that the Eclipse ADT pluginis installed .

  1. Open     Eclipse
  2. Right     click on the Android Test project → Build Path → Configure Build Path... →     Libraries → Add External Jars
  3. Select     the android_webdriver_library.jar

If you would like tostep in the code for debugging or see the javadoc from Eclipse, it’srecommended you link the sources as well.

  1. Open     the Referenced Libraries
  2. Right     click on android_webdriver_library.jar → Properties → Java Source     Attachment
  3. Select     android_webdriver_library-srcs.jar

Let's import theexamples and run the sample code:

  1. Open     Eclipse
  2. File     → Import... → General → Existing Projects into Workspace
  3. Select     the directory your_android_sdk/extras/google/webdriver which contains     SimpleApp and TestAnAndroidWebApp projects.
  4. Right     click on TestAnAndroidWebApp → Run As → Android JUnit Test

You will see thetests executing on your device or emulator.

Configuringcommand line managed projects

If you are managingyou project from the commandline, copy android_webdriver_library.jar under the /libs directory of yourAndroid test project. First we need to build and install the SimpleAppapplication.

$ cd SimpleApp 
$ adb update project 
$ ant debug 
$ adb install bin
/SimpleAppActivity-debug.apk

Then let's build andinstall the test application:

$ cd TestAnAndroidWebApp 
$ adb update test project 
$ ant debug 
$ adb install bin
/TestAnAndroidWebApp-debug.apk

Now we can run thetests! Execute the following command to see your tests running:

$ adb shell am instrument -wsimple.app.test/android.test.InstrumentationTestRunner

Android WebDriverrequires the following permissions in the application's manifest file to workproperly:

  • android.permission.INTERNET    
  • android.permission.ACCESS_NETWORK_STATE    
  • android.permission.WRITE_SETTINGS    
  • android.permission.WAKE_LOCK    
  • android.permission.CLEAR_APP_CACHE    
  • android.permission.ACCESS_COARSE_LOCATION    
  • android.permission.ACCESS_MOCK_LOCATION    
  • android.permission.ACCESS_FINE_LOCATION    
  • android.permission.ACCESS_LOCATION_EXTRA_COMMANDS    
  • android.permission.CHANGE_CONFIGURATION    
  • android.permission.SET_DEBUG_APP    
  • android.permission.WRITE_EXTERNAL_STORAGE    
  • android.permission.WRITE_APN_SETTINGS    

Get Involved

Want to fix a bug?Add a feature? Or simply play with the code? Here is a quick tutorial to helpyou get started with Android WebDriver.

  • Check     out the code:

$ svn checkout https://selenium.googlecode.com/svn/trunk/webdriver 
$ cd webdriver

Edit the properties.yml file to reflect thelocation of your Android SDK, and set the platform target you want to use. Ifyou want a list of all available target, execute the following command:

./android listtargets

On Linux, android SDKis distributed for 32-bits machine. If you have a 64-bit machine you will needto install ia32-libs http://developer.android.com/sdk/installing.html#troubleshooting

Build the Android WebDriver Code

Android WebDriverconsists of 3 parts. The client and the server used to run Android WebDrivertests remotely, and a library. The library does most of the real work and isused by Android WebDriver to control the WebView. The server piece simply wrapsthe library in an Android application together with the HTTP server.

  • To     build the library, the client and the server

$./goandroid

  • To     build the client

$./goandroid_client

  • To     build the server

$./goandroid_server

  • To     build the library

$./go //android/library/src/java/org/openqa/selenium/android:android_library

  • To     run the tests

$./gotest_android

This command willstart the emulator install the Android WebDriver application and start thetests.

If theemulator/device screen is locked, simply unlock it to see the tests running.

Note that "./gotest_android" will fail if there is already an emulator running.

Update the Atoms Usedby Android WebDriver

First let's build allthe fragment Android WebDriver uses:

./go //javascript/android-driver:atoms

Then copy the newAndroidAtoms.java:

cp build/javascript/android-driver/AndroidAtoms.javajava/client/src/org/openqa/selenium/android/library/AndroidAtoms.java

Compile and run thetests to make sure nothing broke! Then make a release of the new APK byfollowing the instructions here.

Debug on Android

  • Run     the tests

It's advised to startyour own emulator instance (instructions above), leave the emulator running andrun the tests. This will prevent you from paying the cost of starting a newemulator for every test run. To run the tests on an already running emulator:

$./go //java/client/test/org/openqa/selenium/android:java-test:run haltοnerrοr=false haltonfailure=false

  • To     run one test class only:

./go //java/client/test/org/openqa/selenium/android:java-test:runonlyrun=LocalStorageTest haltοnerrοr=false haltonfailure=false

  • To     run one test method only:

./go //java/client/test/org/openqa/selenium/android:java-test:runmethod=testShouldTreatReadonlyAsAValue

  • To     access the Android logs (server side logs):

$./adblogcat

The Android logcatlogs are the most useful piece of information for debugging and fixing anissue. You can also filter the logs by adding "ActivityMAnager:W" forexample to the logcat command.

  • To     access the JS console:

- Open the androidbrowser - Type "about:debug" in the address bar, this is a togglesetting that will enable the JS console - Execute Js in the browser by typingjavascript:<your JS>, you will see the JS console opening

  • View     the client side logs:

$ls build/test_logs/

Make a Release

To release an apk,build the new apk:

$ ./go //android:android-server

Check-in the newprebuilt apk:

$ svn ci android/prebuilt/android-server.apk

Upload the new APK onthe downloads page with the corresponding release notes.

FAQ

My tests are slow,what can I do?

  • Avoid     looking up elements by XPath, it is by far more expensive than using IDs     or name.
  • Keep     the same emulator instance for all tests. Starting an Android emulator is     an expensive operation which can take up to 2 minute depending on your     machine specifications. Do this once for your entire test suite. If you     need a fresh instance of the driver call WebDriver.quit() which flushes     the WebView cache, cookies, user data, etc.
  • Prefer     window handles to window names (e.g. String current =     driver.getWindowHandle(); driver.switchTo().window(current);). Switching     to a window by it's name property is more expensive because it requires     injecting Javascript in every open window to fetch the window's name.     While handles are saved in map which provides really fast lookup times.

The emulator is tooslow to start

The Android emulatorcan take up to 2 or 3 minutes to start. Consider using the Android snapshotfeature, which allows you to start an emulator in less than 2 seconds!

You can speed up thetests by disabling animations, audio, skins, and even by running in headlessmode. To do so start the emulator with the options --no-boot-anim, --no-audio,--noskin, and --no-window.

If you start theemulator with -no-window, you can launch the WebDriver app with this command:

$adb shell am start -aandroid.intent.action.MAIN-n org.openqa.selenium.android.app/.MainActivity

Or in debug mode:

 $adb shell am start -aandroid.intent.action.MAIN-n org.openqa.selenium.android.app/.MainActivity-edebug true

Geo location does not work

  • Remember     to set the following settings on your device: Settings -> Applications     -> Development -> Check "USB debugging", "Stay     Awake" and "Allow mock locations"

ADB does not find theemulator or device

  • Sometimes     there are issues connecting to the device / emulator in which case you can     restart adb by doing:

$ adb kill-server 
$ adb start
-server

How to start the HTTPserver Jetty

Jetty is started bythe Android WebDriver application when launched.

I get "Page notAvailable"

Sometimes the Androidemulator does not detect the connection of the host machine it runs on. Thesolution in this case is to restart the emulator.

Android WebDriverfails to load HTTPS pages

You can enableaccepting all HTTPS certs by setting a capability as follow:

DesiredCapabilitiescaps =DesiredCapabilities.android(); 
caps
.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true); 
 
AndroidDriver driver =newAndroidDriver(caps);

Can't talk to theemulator or device

Sometimes executingadb commands will fail because the adb server fails to talk to the device oremulator. To fix this kill the adb server and restart it:

$adb kill-server 
 
$adb start
-server

Inconsistent certificateswhen installing the apk

You may see thefollowing error when trying to install an apk:

Failure[INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]

This means that thecertificates used to sign the apk are different from the certificate used withthe already installed apk. To fix this, unistall the current apk:

$adb uninstall org.openqa.selenium.android.app/.MainActivity

You can alsouninstall an app manually, by opening the Settings -> Applications ->select WebDriver -> Uninstall.

Can't access theAndroid WebDriver server from another machine

If you want to accessthe Android WebDriver server from another machine (or an interface which isn'tlocalhost), do the following after doing the port forwarding:

# Instal socat, one time setup 
$sudo apt
-get install socat 
 
$socat TCP
-LISTEN:8081,forkTCP:localhost:8080

Now the AndroidWebDriver server can be accessed from http://hostname:8081/wd/hubfrom any machine or network interface.

X compatibility

Note: The androidemulator is not compatible with xvfb, and will not run in it. If you need aheadless X environment, run your emulator with the -no-window option, or usetightvncserver.

 

 

http://jarvi.iteye.com/blog/1447389

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值