Amdroid Web driver

http://code.google.com/p/selenium/wiki/AndroidDriver
Introduction
Android WebDriver allows to run automated end-to-end tests that ensure your site works correctly when viewed from the Android browser. Android WebDriver supports all core WebDriver APIs, and in addition to that it supports mobile spacific and HTML5 APIs. Android WebDriver models many user interactions such as finger taps, flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5 features such as local storage, session storage and application cache.

We try to stay as close 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 by the Android browser) configured like the Android browser. To interact with the page Android WebDriver uses native touch and key events. To query the DOM, it uses 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
Android WebDriver on Android Blog
Android WebDriver on Google Open Source Blog
Get Started
Install the Android SDK
Download the Android SDK, and unpack it in a directory, say ~/android_sdk/ .

Setup the Environment
Android WebDriver test can run on emulators or real devices for phone and tablets.

Setup the Emulator
To create an emulator, you can use the graphical interface provided by the Android SDK, or the command line. Below are instructions for using the command line.

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

$cd ~/android_sdk/tools/
$./android create avd -n my_android -t 12 -c 100M
-n: specifies the name of the AVD.

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

./android list targets
Make sure the target level you selected corresponds to a supported SDK platform.

-c: specifies the SD card storage space.

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

Note: An Android emulator bug prevents WebDriver from running on emulators on platforms 2.3 (Gingerbread).

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

$./emulator -avd my_android &
Setup the Device
Simply connect your Android device through USB to your machine.

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

Using the remote WebDriver server
Using the Android test framework
Here is a comparaison 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 a client and a server component. The client consists of your typical Junit tests that you can run from your favorite IDE or through the command line. The server is 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 using JSON according to a well defined protocol. The remote server will delegate the request to Android WebDriver, and will then return a response.

Install the WebDriver APK
Every device or emulator has a serial ID. Run this command to get the serial ID of the device or emulator you want to use:

$~/android_sdk/platform-tools/adb devices
Download the Android server from our downloads page. To install the application do:

$./adb -s <serialId> -e install -r android-server.apk
Make sure you are allowing installation of application not coming from Android Market. Go to Settings -> Applications, and check "Unknown Sources".

Start the Android WebDriver 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 the application 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 -e debug true
Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. In a terminal type:

$./adb -s <serialId> forward tcp:8080 tcp:8080
This will make the android server available at http://localhost:8080/wd/hub from the host machine. You're now ready to run the tests. Let's take a look at some code.

Run the Tests
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 from the element
element.submit();

// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
To compile and run this example you will need the selenium-java-X.zip (client side piece of selenium). Download the selenium-java-X.zip from our download page, unzip and include all jars in your IDE project. For Eclipse, right click on project -> Build Path -> Configure Build Path -> Libraries -> Add External Jars.

Using the Android Test Framework
This approach runs the tests directly on the device using the Android test framework.

You first need to download Android WebDriver, which is an SDK extra. Open the Android SDK manager and select: Available packages → Extras → Google → WebDriver. Once the SDK manager has downloaded WebDriver, the jars will be under the directory android_sdk/extras/google/webdriver/ . In the same directory you will also find sample code containing and Android project named "SimpleApp" and an Android test project called "TestAnAndroidWebApp".

The SimpleApp project, contains an activity with no layout:

public class SimpleAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
The reason the activity does not have any layout is because Android WebDriver will create the WebView and automatically set the layout in that activity.

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

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

WebDriver driver = new AndroidWebDriver(getActivity());
Then we use the driver in a test to drive the web application.

public void testGoogleWorks() {
// Loads www.google.com
driver.get("http://www.google.com");
// Lookup the search box on the page by it's HTML name property
WebElement searchBox = driver.findElement(By.name("q"));
// Enter keys in the search box
searchBox.sendKeys("Android Rocks!");
// Hit enter
searchBox.submit();
// Ensure the title contains "Google"
assertTrue(driver.getTitle().contains("Google"));
// Ensure that there is at least one link with the keyword "Android"
assertTrue(driver.findElements(By.partialLinkText("Android")).size() > 1);
}
Here a are some instructions to help you setup you project.

Configuring from an Eclipse Project
If you are using Eclipse, first make sure that the Eclipse ADT plugin is installed .

Open Eclipse
Right click on the Android Test project → Build Path → Configure Build Path... → Libraries → Add External Jars
Select the android_webdriver_library.jar
If you would like to step in the code for debugging or see the javadoc from Eclipse, it’s recommended you link the sources as well.

Open the Referenced Libraries
Right click on android_webdriver_library.jar → Properties → Java Source Attachment
Select android_webdriver_library-srcs.jar
Let's import the examples and run the sample code:

Open Eclipse
File → Import... → General → Existing Projects into Workspace
Select the directory your_android_sdk/extras/google/webdriver which contains SimpleApp and TestAnAndroidWebApp projects.
Right click on TestAnAndroidWebApp → Run As → Android JUnit Test
You will see the tests executing on your device or emulator.

Configuring command line managed projects
If you are managing you project from the command line, copy android_webdriver_library.jar under the /libs directory of your Android test project. First we need to build and install the SimpleApp application.

$ cd SimpleApp
$ adb update project
$ ant debug
$ adb install bin/SimpleAppActivity-debug.apk
Then let's build and install the test application:

$ cd TestAnAndroidWebApp
$ adb update test project
$ ant debug
$ adb install bin/TestAnAndroidWebApp-debug.apk
Now we can run the tests! Execute the following command to see your tests running:

$ adb shell am instrument -w simple.app.test/android.test.InstrumentationTestRunner
Android WebDriver requires the following permissions in the application's manifest file to work properly:

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 help you 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 the location of your Android SDK, and set the platform target you want to use. If you want a list of all available target, execute the following command:

./android list targets
On Linux, android SDK is distributed for 32-bits machine. If you have a 64-bit machine you will need to install ia32-libs http://developer.android.com/sdk/installing.html#troubleshooting

Build the Android WebDriver Code
Android WebDriver consists of 3 parts. The client and the server used to run Android WebDriver tests remotely, and a library. The library does most of the real work and is used by Android WebDriver to control the WebView. The server piece simply wraps the library in an Android application together with the HTTP server.

To build the library, the client and the server
$./go android
To build the client
$./go android_client
To build the server
$./go android_server
To build the library
$./go //android/library/src/java/org/openqa/selenium/android:android_library
To run the tests
$./go test_android
This command will start the emulator install the Android WebDriver application and start the tests.

If the emulator/device screen is locked, simply unlock it to see the tests running.
Note that "./go test_android" will fail if there is already an emulator running.

Update the Atoms Used by Android WebDriver
First let's build all the fragment Android WebDriver uses:

./go //javascript/android-driver:atoms
Then copy the new AndroidAtoms.java:

cp build/javascript/android-driver/AndroidAtoms.java java/client/src/org/openqa/selenium/android/library/AndroidAtoms.java
Compile and run the tests to make sure nothing broke! Then make a release of the new APK by following the instructions here.

Debug on Android
Run the tests
It's advised to start your own emulator instance (instructions above), leave the emulator running and run the tests. This will prevent you from paying the cost of starting a new emulator 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:run onlyrun=LocalStorageTest haltοnerrοr=false haltonfailure=false
To run one test method only:
./go //java/client/test/org/openqa/selenium/android:java-test:run method=testShouldTreatReadonlyAsAValue
To access the Android logs (server side logs):
$./adb logcat
The Android logcat logs are the most useful piece of information for debugging and fixing an issue. You can also filter the logs by adding "ActivityMAnager:W" for example to the logcat command.

To access the JS console:
- Open the android browser - Type "about:debug" in the address bar, this is a toggle setting that will enable the JS console - Execute Js in the browser by typing javascript:<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 new prebuilt apk:

$ svn ci android/prebuilt/android-server.apk
Upload the new APK on the 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 too slow to start
The Android emulator can take up to 2 or 3 minutes to start. Consider using the Android snapshot feature, which allows you to start an emulator in less than 2 seconds!

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

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

$adb shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity
Or in debug mode:

$adb shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug 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 the emulator 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 HTTP server Jetty
Jetty is started by the Android WebDriver application when launched.

I get "Page not Available"
Sometimes the Android emulator does not detect the connection of the host machine it runs on. The solution in this case is to restart the emulator.

Android WebDriver fails to load HTTPS pages
You can enable accepting all HTTPS certs by setting a capability as follow:

DesiredCapabilities caps = DesiredCapabilities.android();
caps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

AndroidDriver driver = new AndroidDriver(caps);
Can't talk to the emulator or device
Sometimes executing adb commands will fail because the adb server fails to talk to the device or emulator. To fix this kill the adb server and restart it:

$adb kill-server

$adb start-server
Inconsistent certificates when installing the apk
You may see the following error when trying to install an apk:

Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]
This means that the certificates used to sign the apk are different from the certificate used with the already installed apk. To fix this, unistall the current apk:

$adb uninstall org.openqa.selenium.android.app/.MainActivity
You can also uninstall an app manually, by opening the Settings -> Applications -> select WebDriver -> Uninstall.

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

# Instal socat, one time setup
$sudo apt-get install socat

$socat TCP-LISTEN:8081,fork TCP:localhost:8080
Now the Android WebDriver server can be accessed from http://hostname:8081/wd/hub from any machine or network interface.

X compatibility
Note: The android emulator is not compatible with xvfb, and will not run in it. If you need a headless X environment, run your emulator with the -no-window option, or use tightvncserver.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值