Sunteți pe pagina 1din 102

Android Application Testing Lab-Guide

Table of Contents
Android Developer Tools.............................................................................................................................................................................................................. 2
Verification Commands ............................................................................................................................................................................................................. 43
Retry Until Timeout ................................................................................................................................................................................................................... 44
Examples .................................................................................................................................................................................................................................... 44
Step 1: Create an Android Application.................................................................................................................................................................................. 63
Step 2: Logging Options for Android Applications .............................................................................................................................................................. 64
Step 3: Adding Log Support to an Activity Class ................................................................................................................................................................. 65
Step 4: Monitoring Application Log Output The Easy Way .................................................................................................................................................. 66
Step 5:Monitoring Application Log Output Creating Log Filters ................................................................................................................................... 67
Performance Considerations with Logging ........................................................................................................................................................................... 68
Conclusion ................................................................................................................................................................................................................................ 69
Opera Mobile Emulator for desktop....................................................................................................................................................................................... 82
Introduction ............................................................................................................................................................................................................................. 93
The Profile Selector ................................................................................................................................................................................................................ 93
Profiles .................................................................................................................................................................................................................................. 93
Resolution ............................................................................................................................................................................................................................ 95
Pixel Density......................................................................................................................................................................................................................... 95
1

User Interface ...................................................................................................................................................................................................................... 95


User Agent String ............................................................................................................................................................................................................... 97
Window Scale ...................................................................................................................................................................................................................... 97
Arguments ............................................................................................................................................................................................................................ 98
Full browser reset on startup ........................................................................................................................................................................................... 98
Launching Opera Mobile instances from the command line ........................................................................................................................................ 98
Input modes: touch, keypad and tablet ............................................................................................................................................................................. 99
Features and settings of the browser ............................................................................................................................................................................... 100

Android Mobile testing step by step:


Setting up your testing environment for Android
To set up your test environment in Eclipse:
1. Download and install the Eclipse ADT plugin, if you havent installed it yet.

Android Developer Tools


ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of tools that are integrated with the Eclipse IDE. It offers you access to
many features that help you test Android applications. ADT provides GUI access to many of the command line SDK tools.

Many of the tools that you can start or run from the command line are integrated into ADT. They include:

Traceview: Allows you to profile your program's execution (Window > Open Perspective > Traceview).

DDMS: Provides debugging features including: screen capturing, thread and heap information, and logcat (Window > Open Perspective >
DDMS).

adb: Provides access to a device from your development system. Some features of adb are integrated into ADT such as project installation
(Eclipse run menu), file transfer, device enumeration, and logcat (DDMS). You must access the more advanced features of adb, such as shell
commands, from the command line.

1. There are two directories in Android SDK


platform-tools
tools

2. How to set the environment path to run Android App.


Right click on computer and select properties

Click on Advance system settings

System properties dialog box will be shown.

Then click on Environment Variables button

In System variables, first select Path, then click on edit button. One dialog box will be shown

Variable name should be path


There will be two Variable values
Specify absolute path of platform-tools folder
Specify absolute path of tools folder
For Example->C:\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\platform-tools;
C:\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools

All paths are separated by semicolons ex (;)


Then click on ok button of Edit system variable
Then click on ok button of Environment variable
Then click on ok button of System Properties

Now, open a cmd window and type adb and hit enter. If you see the following output, we are going good.

SDK manager
The Android SDK Manager manages the various versions of the Android SDK currently installed
on your computer.
Go to C:\adt-bundle-windows-x86_64-20131030 and double click SDK Manager.exe
When it is launched, you will see a list of items and whether or not they are

10

currently installed on your computer.

select the relevant tools, documentation, and platforms you need for your project.
click the Install button to download them. Because it takes a while
to download from Googles server, it is a good idea to download only what you need immediately,
and download the rest when you have spare time. Once the setup is complete, You can zip the entire setup
and share with anybody.
11

12

3. How to create AVD configuration?

Open adt-bundle tool.

13

14

4. How to start the emulator from command line?


On command line type emulator avd AVD2
Then press on enter key.
Android emulator will be displayed. It may take a few minutes to start.

Then unlock the emulator

15

Then click on
in start icon.
Your Android project will be displayed
Single click on <Name of Project Icon>
16

4. How to install an Android Application on emulator from command line.


Type adb install <path of apk file>

Then press enter key


Then message will be shown success on command line.

17

18

Single click on

Icon Mobile App will be displayed.

5. How to Uninstall an Android Application on emulator from command line.


19

adb uninstall <base package name>

press enter key


Then message will be show success on command line
Note: <base package name> will be provided by the development team.
6. To know how many devices are currently connected to the system.

7. How to test an Android Application using Monkeytalk tool


1. Install monkeytalk and configure it.

20

2. Go to window -> preference -> select MonkeyTalk Prefrences


3. Specify the Android SDK in your system like. E:\Veritas\adt-bundle-windows-x86\sdk
4. Specify default think time and Timeout in milliseconds
21

5. Press Apply and Ok


6. In monkeytalk IDE select File->New->Monkeytalk project.

7. Write the name Project and click on finished button

22

8. Project Structure will come like below.

23

9. How to create a test script file.


No need to give extension .mt

24

10.How to use MonkeyTalk script for recording tests?


25

Play button

Recording Stop Button


Recording Button

11.Enter the user and password like below.


11.1 first click on recording button then enter the values
11.2 click on stop button.
26

11.3 All steps will be captured logintest.mt file like below


11.4 if no error found in Application then last message show on console Completed Script playback-OK.
27

11.5 The Logout button will take some time to execute. We can slow the execution by giving a higher Think
Time( 8000 ms).

Means No Error and script run successfully

28

13 How to create a test suite to test multiple scripts.

There are two script files. First is login.mt and second is formtest.mt. In login.mt, First I have inserted one row
in first row, in component column I have entered Vars , Monkeyid should be * action select define, arguments
column specify two variables one first user and second for password, both separated by space. Both variable
29

we have to write corresponding fields like ${userName}, ${password} and formtest script we have also tap
some kind. Like recording ,stop and click on play all.

12.Creating testsuite file.

In above select File->new->TestSuite-><enter name of file>


30

13.

31

In above testsuite.mts in component column select Test , MonnkeyId column -> name of script file
login, action column select Run and argument column write user1, pass1-> values are coming
fromlogin page and second row and so do same kind.

13. How to verify values?

32

14.How to test with parameterized values.


33

Login.mt script

Formtest.mt
34

14.1 First we need to create login.mt script tap the login value
Above I have created script file first is login.mt and second is formtest.mt. In login.mt first I have
inserted one row in first row, in component column I have entered Vars , MonkeyId should be *action
select define, arguments column specify two variables one first user and second for password, both
separated by space. Both variable we have to write corresponding fields like ${userName}, ${password}
and formtest script we have also tap some kind. Like recording ,stop and click on play all.

14.2 Create testSuite Go to File->New->select testSuite


35

14.3 In testSuite script file, right click and select append row to create a new editable row.

36

14.4 in first row component column select Test in monkeyId column Enter script file name ex login , action
column select Runwith and arguments enter input.csv that file is used to store the data.

15.5 How to make input.csv file

37

14.5 give the name of file is input.csv and enter variables username, password first value user1, pwd1 second
value user2, pwd2.

14.6 click on run at testsuite icon

then above data run at emulator like show below


38

login.mt

Testform.mt

When successfully run the monkeytalk show like that.


39

14.7 First you copy the runTest.xml file to your monkeytalk project.
15.How to work with Automated testing.

Or
40

FileNamerunTest.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="MyTests" xmlns:monkeytalk="antlib:com.gorillalogic.monkeytalk.ant">
<target name="mySuite">
<monkeytalk:run agent="AndroidEmulator"
adb="E:\Veritas\adt-bundle-windows-x86\sdk\platform-tools\adb.exe"
script="testSuite.mts"
reportdir="${basedir}/androidreports"
thinktime="4000"
timeout="5000"
adbSerial="emulator-5554"
verbose="true" />
</target>
<target name="mySuites">
<monkeytalk:run agent="AndroidEmulator"
adb="E:\Veritas\adt-bundle-windows-x86\sdk\platform-tools\adb.exe"
script="testSuite1.mts"
reportdir="${basedir}/androidreports"
thinktime="4000"
timeout="5000"
adbSerial="emulator-5554"
verbose="true" />
</target>

15.1 Each target work like method and you have to specify adb location in your computer
15.2 adb="E:\Veritas\adt-bundle-windows-x86\sdk\platform-tools\adb.exe"
15.3 then after you have to write the name of the test file like script="testSuite.mts"
16.3 Test the ant is install in tour computer o r not

Iifif not install then go computer->property->single click on advanced system setting->click on environment
variable->go to system variables->select path-> C:\Program Files\Java\jdk1.6.0_03\bin and click on
ANT_HOME->E:\Veritas\adt-bundle-windows-x86\sdk\platform-tools;
41

1616.4 start the emulator and install the application and specify the location of monkeytalk-ant1.0.11.beta5c.jar and target file like mySuite
/5\

16.516Then go command line and write ->ant lib"E:\Veritas\Software\monkeytalk32\monkeytalk\ant\monkeytalk-ant1.0.11.beta5c.jar " f


"E:\Veritas\Software\monkeytalk32\monkeytalk\MonkeyTalkIDE\workspace\monkeytests\runTests.xml" mySuite

After build successful your application runs in emulator.

42

15.4
15.5 16
Verification Commands
Add a Verify command at each point in your script where you want to test that an actual value matches an expected one.
There are several different Verify commands that differ in how they compare expected and actual values.

Verify - Verify that the component's value is equal to the argument.


VerifyNot - Verify that the component's value is NOT equal to the argument.
VerifyRegex - Verify that the component's value matches the Regular Expression provided in the argument.
VerifyNotRegex - Verify that the component's value does NOT match the Regular Expression provided in the argument.
VerifyWildcard - Verify that the component's value matches some wildcard expression provided in the argument.
43

VerifyNotWildcard - Verify that the component's value does NOT match some wildcard expression provided in the
argument.
General form of verify commands:
ComponentType MonkeyId Verify expectedValue [propertyName] [failMsg]
The popertyName can be a "built-in" or "native" property. Like component types, Built-in properties are platformindependent. Built-in properties are defined for commonly used propeerties.
The default property is the built-in value property which returns the current display value of the component. Other built-in
properties for MonkeyTalk component types are documented in the Command Reference.
Native properties can be any property on the underlying platform-specific component. See the documentation of the
platform's sdk to see the available component properties.
Retry Until Timeout
You can specify a timeout on a verify command to lengthen or shorten the amount of time for which verification should
occur before a timeout.
Examples
Slider Speed Verify 123 value
Label Greeting VerifyWildcard "Hello *"
Input ssn VerifyRegex \d{3}-\d{2}-\d{4} value "Invalid SSN"
# Allow a max of 4 seconds for welcome meesage to appear
Label Greeting VerifyWildcard "Hello *" %timeout=4000

16. How to test Multiple scriptswith a test-suite.


16.1 First we have to create two or more script file
16.2 Then create one TestSuite file and the name of file.

44

16.3 TestSuite file should have extension


8. Orientation of emulator.
Portrait
Landscape
To orientation Command: ctrl +F11

45

Portrait

46

Landscape:

Chapter 3
Working with Sqlite database.
Notepad Application details.
47

This notepad Mobile Application is used to insert records in Sqlite database. In this application database
name is note_pad.db and inside db table name is notes.
3.1 First step to install notepad App in emulator.

3.2 Single c click on Notes


to save the records in database.

icon then display Application and enter the records and click on save

icon

48

3.4 Showing the records in emulator whatever I have entered.

49

3.5 How to see whether the data save in database or not


1. Method 1.
50

3.5.1 Single click on DDMS

icon.

3.5.2 Select the devicesemulator then we will got file system->File explorerthen go to->data again>datathen go to project directories (com.example.android.notepad) then click on databases and table name note_pad.db.
51

3.5.3 First we pull in out to click on

icon. Then specify the location where we want to save db file.

52

Click on save button.

53

3.6 How to see the data through command prompt.


3.6.1 Open the command prompt like below

54

3.6.2 write Sqlite3 on command prompt and specify the location of db and hit enter.

3.6.3 Then Sqlite command prompt will come.


55

3.6.4How to know the Table name.


56

3.6.5 How to show schema of tables.

57

.schema : we can see the list of tables.

58

3.6.5 How to show data inside tables.

59

4. How to capture logs from Android?

adb logcat
Then press enter them showing below log file
How to show the logs when multiple emulator are running.

60

If adb devices command does not detect the emulator, then run the following two command.

How to keep all log in one file.


61

Method 2. Without pulling


1. 3 First you click on DDMS icon

then DDMs window will be display

1. Select the devicesemulator then we will got file system->File explorer then go to->data

again->data then go
to project directories(com.example.android.notepad) then click on databases and table name note_pad.db.

In above command direct connect to database without fulling.

2. How to know structure of table


62

.schema <table name>


3. How to show list of table in database.

4. How to show header of table

5. How to show records from table with header.

6. How to show the schema of table

Step 1: Create an Android Application


63

Begin by creating an Android project. Implement your Android application as normal. Once youve setup your Android
project, you are ready to proceed with this quick tip.
Step 2: Logging Options for Android Applications
The Android SDK includes a useful logging utility class called android.util.Log. Logging messages are categorized by
severity (and verbosity), with errors being the most severe, then warnings, informational messages, debug messages and
verbose messages being the least severe. Each type of logging message has its own method. Simply call the method and a
log message is created. The message types, and their related method calls are:

The Log.e() method is used to log errors.


The Log.w() method is used to log warnings.
The Log.i() method is used to log informational messages.
The Log.d() method is used to log debug messages.
The Log.v() method is used to log verbose messages.
The Log.wtf() method is used to log terrible failures that should never happen. (WTF stands for What a Terrible
Failure! of course.)

The first parameter of each Log method is a string called a tag. Its common practice to define a global static string to
represent the overall application or the specific activity within the application such that log filters can be created to limit the
log output to specific data. For example, you could define a string called TAG, as follows:
1. private static final String TAG = "MyApp";
You will often find that the tag is defined as the class in which the Log statement occurs. This is a reasonable convention,
but anything identifiable or useful to you will do.
Now anytime you use a Log method, you supply this tag. An informational logging message might look like this:
1. Log.i(TAG, "I am logging something informational!");
64

You can also pass a Throwable object, usually on Exception, that will allow the Log to print a stack trace or other useful
information.
1.
2.
3.
4.
5.

try {
// ...
} catch (Exception exception) {
Log.e(TAG, "Received an exception", exception);
}

NOTE: Calling the Log.wtf() method will always print a stack trace and may cause the process to end with an error
message. It is really intended only for extreme errors. For standard logging of exceptions, we recommend using the Log.e()
method. The Log.wtf() method is available only in Android 2.2 or later. The rest are available in all versions of Android.
Step 3: Adding Log Support to an Activity Class
Now lets add some logging to your Activity class. First, add the appropriate import statement for the logging class
android.util.Log. Next, declare a logging tag for use within your class (or whole application); in this case, we call this
variable DEBUG_TAG. Finally, add logging method calls wherever you want logging output. For example, you might add
an informational log message within the onCreate() method of your Activity class.
Below is some sample code that illustrates how all these steps come together:
1.
2.
3.
4.
5.
6.
7.
8.
9.

package com.mamlambo.simpleapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MySimpleAppActivity extends Activity {
private static final String DEBUG_TAG= "MySimpleAppLogging";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
65

10.
setContentView(R.layout.main);
11.
Log.i(DEBUG_TAG, "Info about MySimpleAppActivity.");
12. }
13.}
Step 4: Monitoring Application Log Output The Easy Way
You can use the LogCat utility from within Eclipse to view the log output from an emulator or device. LogCat is integrated
into Eclipse using the Android Development plug-in. Youll find the LogCat panel integrated into the DDMS and Debug
perspectives of Eclipse.

66

Step 5:Monitoring Application Log Output Creating Log Filters


As you can see, the basic LogCat logging output includes log data from lots of different sources. For debugging purposes, it
can be useful to filter the output to only the tags for your specific application. This way, you can focus on your application
log output, amidst all the clutter.
67

You can use the LogCat utility from within Eclipse to filter your log messages to the tag string you supplied for your
application. To add a new filter, click the green plus sign button in the LogCat pane of Eclipse. Name the filterperhaps
using the tag nameand fill in the tag you want to filter on. A new tab is created in LogCat that will show only log
messages that contain this tag. You can create filters that display items by severity level.

Performance Considerations with Logging


Logging output puts a damper on application performance. Excessive use can result in decreased application performance.
At minimum, debug and verbose logging should be used only for development purposes and removed before release. Its
also a good idea to review other logging output before publication as well.
68

Conclusion
Logging is a very handy debugging and diagnostic technique used by developers. Use the logging class provided as part of
the Android SDK to log important information about your application to LogCat, but make sure you review your
applications logging implementation prior to publication, as logging has performance drawbacks.

Common problems:

oi
Emulator keyboard mapping
Emulated Device Key

Keyboard Key

Home

HOME

Menu (left softkey)

F2 or Page-up button
69

Star (right softkey)

Shift-F2 or Page Down

Back

ESC

Call/dial button

F3

Hangup/end call button

F4

Search

F5

Power button

F7

Audio volume up button

KEYPAD_PLUS, Ctrl-F5

Audio volume down button

KEYPAD_MINUS, Ctrl-F6

Camera button

Ctrl-KEYPAD_5, Ctrl-F3

Switch to previous layout orientation (for example,


portrait, landscape)

KEYPAD_7, Ctrl-F11

Switch to next layout orientation (for example,


portrait, landscape)

KEYPAD_9, Ctrl-F12

Toggle cell networking on/off

F8

Toggle code profiling

F9 (only with -trace startup option)

Toggle fullscreen mode

Alt-Enter

Toggle trackball mode

F6
70

Enter trackball mode temporarily (while key is


pressed)

Delete

DPad left/up/right/down

KEYPAD_4/8/6/2

DPad center click

KEYPAD_5

Onion alpha increase/decrease

KEYPAD_MULTIPLY(*) /
KEYPAD_DIVIDE(/)

Monkeytalk Commands.
MonkeyTalk

Device

Action

Description

Example for android

Rotate

This method is used for Change the device


orientation.
Android:Landscape,Portrait
Ios:Left,Right

Device * Rotate Landscape

Back

iOS: Pops the current UINavigationItem (if


there is one)
Android: Presses the hardware device key

Device * back

forward

iOS: Pushes the next UINavigationItem, if there


is one
N/A on Android.
Android: ignored.

71

search

iOS: ignored.
Android: Presses the device search key.

Device * Search

Screenshot

This method is used to create screenshot folder


in running project and we can capture
screenshot at any point

Device * Screenshot

Menu

Android: Presses the device menu key.


iOS: ignored

Device * Menu

Shake

This method is used for specific apps.

Device * Shake

Get

This method returns iOS or Android.

Device * Get a

Select

This method is used to select an element from


the table.

Table * Select Boron

SelectRow

Select a row.
row the row to select
section the section containing the row.
(Ignored on Android).
Where row and section are arguments.

ScrollToRow(by
row)

Scroll to a row by row number.


Row the row to select
section the section containing the row.
(Ignored on Android).
Where row and section are arguments and both

Table

72

args should be integer.


ScrollToRow(by
Value)

Scroll to a row by value.


value (int)- the value of the row to scroll to.

SetEditing

Enable/disable table editing. iOS: Enabled


editing mode for table. Android: ignored.

N/A on Android.

Insert

Insert a row into the table. iOS: Inserts a row.


Android: Ignored.

N/A on Android.

Remove

Remove a row from the table. iOS: Deletes the


N/A on Android.
row. Android: Ignored.

Move

Move a row. iOS: Moves a row. Android:


Ignored

N/A on Android.

Selects an item by index.

Table * SelectIndex 3
Where 3 is item no i.e index and
index should be integer.

LongSelectIndex

Long press an item by index.

Table * LongSelectIndex 4
Where 4 is item no i.e index and
index should be integer.

verify

Syntax: ComponentType
Verifies that a property of the component has
some expected value.If Expected value is null MonkeyId Verify arg
then it verifies the existence of the component. where for argument pass
expected value for verification

SelectIndex

View

73

and componenttype can be any


component of monkeytalk like
label,button,tabbar etc.
Example: Label #1 Verify
Welcome, test!
%thinktime=8000
Label LOGOUT Verify
LOGOUT %thinktime=3000
or
View LOGOUT Verify
LOGOUT %thinktime=3000

verifyNot

Verifies that a property of the component does


not have some value.If Expected value is null
then it verifies the non-existence of the
component.

verifyRegex

Verifies that a property of the component


matches some regular expression.

verifyNotRegex

Verifies that a property of the component does


not have a value matching a regular expression

verifyWildcard

Verifies that a property of the component does


have a value matching some wildcard

ComponentType MonkeyId
VerifyNot arg
Label LOGOUT VerifyNot
Login %thinktime=3000
or
View LOGOUT VerifyNot
Login %thinktime=3000

74

expression

verifyNotWildcard

Verifies that a property of the component does


not have a value matching some wildcard
expression

Get

Retrieves a property value from the component

Syntax: ComponentType
MonkeyId Get Variable
PropPath
Example: Button LOGIN Get b
:text
Label #1 Get a

Tap

Taps on the component. On Android, plays a


click. On iOS, plays a
TouchDown/TouchMove/TouchUp sequence.

Button LOGOUT Tap

Swipe

Swipe(scroll) the component in direction Left,


Right, Up, or Down (case insensitive)

WebView webview swipe Down


Table * Swipe Up
Slider * Swipe Right

Touch down, drag across the component, then


up

Input username Drag 43 154 181


162
where 43 and 154 are x1,y1 i.e
starting cordinates and 181 &
162 are x2,y2 i.e ending
cordinates.

Drag

75

TouchDown

Start touching the component.

Input username TouchDown 43


154
where 43 and 154 are x and y
cordinates of touch and x,y
should be integer.

TouchMove

Drag across the component.


one or more (x,y) coordinate pairs specifying
the path of the drag gesture

Input username TouchMove 146


170

TouchUp

Stop touching the component

Input username TouchUp 43 154


where 43 and 154 are x and y
cordinates of touch where touch
is released and x,y should be
integer.

Pinch

Pinch the component.


scale The scale factor relative to the points of
the two touches in screen coordinates
velocity The velocity of the pinch in scale
factor per second (read-only)

Exec

Call a method on a component. The method


must take zero or more String arguments and
return a String result.

Not implemented yet by gorilla


logics.

LongPress

Performs a long press on the component. On


Android, plays a longClick. On iOS, plays a

View LOGOUT LongPress


Button LOGIN LongPress
76

longPush gesture
ButtonSelector forms_radios
select A

Select

Select an item by value.

SelectIndex

Selects an item by index.

LongSelectIndex

Long press an item by index.

EnterText

Enter text into the input field.


text the text to enter
hitDone iOS: if true, hit Done key after
entering text. Android: ignored.
Where text and hitdone are arguments of
entertext action.

Input username EnterText test

Clear

Clear text from the input field

Input username Clear

Run

Run the script with the given args.

Script test1.mt Run john my


password %thinktime=3000

RunWith

Run the script with the given CSV file.

Script datdriven.mt RunWith


credentials.csv

Slider

Select

Select a numeric component value

Slider forms_slider_bar Select 52


%thinktime=3000

TabBar

Select

Select an item by value.

TabBar * Select hierarchy

ButtonSelector

Input

Script

77

%thinktime=1000
TabBar * SelectIndex 2
%thinktime=5000

SelectIndex

Selects an item by index.

LongSelectIndex

Long press an item by index.

Define

Define the named variables used in the script.

On

This action sets or returns the checked state of a


CheckBox forms_checkbox on
checkbox.

Off

This action sets or returns the Unchecked state


of a checkbox.

CheckBox forms_checkbox off

Select

Select an item by value.

ItemSelector * Select Carbon

SelectIndex

Selects an item by index.

ItemSelector * SelectIndex 8

LongSelectIndex

Long press an item by index.

ItemSelector * LongSelectIndex
8

Button

Tap

Taps(click) on the Button. On Android, plays a


click. On iOS, plays a
TouchDown/TouchMove/TouchUp sequence.

Button LOGOUT Tap

DatePicker

EnteDate

Change the current date value.


A date with the format YYYY-MM-DD where
YYYY is the year, MM is the month (01-12),

Vars

Vars * Define user pass

CheckBox

ItemSelector

78

and DD is the day (01-31).


NumericSelector select

Select a numeric component value

RatingBar

select

Select a numeric component value

scroll

Scroll to the specified coordinates.


x the x-coordinate (horizontal)
y the y-coordinate (vertical)

EnterText

Enter text into the input field.


text the text to enter
hitDone iOS: if true, hit Done key after
entering text. Android: ignored.
Where text and hitdone are arguments of
entertext action.

TextArea * enterText This is a


textarea

Clear

Clear text from the input field

TextArea * Clear

SelectIndex

Selects an item by index.

LongSelectIndex

Long press an item by index.

Play

Play the video from the current playback point.

Pause

Stop the video at the current playback point

Stop

Stop the video and set playback to the starting

Scroller

TextArea

ToolBar

VideoPlayer

79

point.
Select

Select an item by value.

Verify

Menu * select About


Menu * Verify About

Menu
SelectIndex

Selects an item by index.

LongSelectIndex

Long press an item by index.

vars

Document the named variables used in the


script.

script

Document the script itself.

Doc

Label

Label #1 Verify Welcome,


test!
Label LOGOUT VerifyNot
LOGIN

All methods of view


are applicable on
label.

Run

Run the setup script with the given args.

SetUp login.mt run john my


password

RunWith

Data-drive the setup script with the given CSV


data file.

SetUp login.mt runwith cre.csv


(where the first arg is the data
file filename )

Run

Run the teardown script with the given args

TearDown logout.mt run

Setup

Teardown

80

RunWith

Data-drive the teardown script with the given


CSV data file.

TearDown logout.mt runwith


logout.csv

Run

Run the test script with the given args.

Test testcase1.mt run

RunWith

Data-drive the test script with the given CSV


data file.

Test testcase1.mt runwith


login.csv

On

Enabled the switch on.

Toggle MonkeyId On

Off

Disabled the switch.

Toggle MonkeyId Off

Test

Toggle

81

Memory analysis in Android

Investigating Your RAM Usage


Because Android is designed for mobile devices, you should always be careful about how much random-access memory
(RAM) your app uses. Although Androids Dalvik virtual machine performs routine garbage collection, this doesnt mean
you can ignore when and where your app allocates and releases memory. In order to provide a stable user experience that
allows the system to quickly switch between apps, its important that your app does not needlessly consume memory when
the user is not interacting with it.
The only way to be certain your app is using as little memory as possible is to analyze your apps memory usage with tools.
This guide shows you how to do that.
Interpreting Log Messages

The simplest place to begin investigating your apps memory usage is the Dalvik log messages. You'll find these log
messages in logcat (the output is available in the Device Monitor or directly in IDEs such as Eclipse and Android Studio).
Every time a garbage collection occurs, logcat prints a message with the following information:
D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>
GC Reason
What triggered the garbage collection and what kind of collection it is. Reasons that may appear include:
GC_CONCURRENT
82

A concurrent garbage collection that frees up memory as your heap begins to fill up.
GC_FOR_MALLOC
A garbage collection caused because your app attempted to allocate memory when your heap was already full, so the
system had to stop your app and reclaim memory.
GC_HPROF_DUMP_HEAP
A garbage collection that occurs when you create an HPROF file to analyze your heap.
GC_EXPLICIT
An explicit garbage collection, such as when you call gc() (which you should avoid calling and instead trust the
garbage collector to run when needed).
GC_EXTERNAL_ALLOC
This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik heap). A garbage
collection for externally allocated memory (such as the pixel data stored in native memory or NIO byte buffers).
Amount freed
The amount of memory reclaimed from this garbage collection.
Heap stats
Percentage free and (number of live objects)/(total heap size).
External memory stats
Externally allocated memory on API level 10 and lower (amount of allocated memory) / (limit at which collection
will occur).
Pause time
Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at the beginning of the
collection and another near the end.
For example:

83

D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms
As these log messages stack up, look out for increases in the heap stats (the 3571K/9991K value in the above example).
If this value continues to increase and doesn't ever seem to get smaller, you could have a memory leak.
Viewing Heap Updates

To get a little information about what kind of memory your app is using and when, you can view real-time updates to your
app's heap in the Device Monitor:
1. Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
2. In the Debug Monitor window, select your app's process from the list on the left.
3. Click Update Heap above the process list.
4. In the right-side panel, select the Heap tab.
The Heap view shows some basic stats about your heap memory usage, updated after every garbage collection. To see the
first update, click the Cause GC button.

84

Figure 1. The Device Monitor tool, showing the [1] Update Heap and [2] Cause GC buttons. The Heap tab on the right
shows the heap results.
Continue interacting with your app to watch your heap allocation update with each garbage collection. This can help you
identify which actions in your app are likely causing too much allocation and where you should try to reduce allocations
and release resources.
Tracking Allocations

As you start narrowing down memory issues, you should also use the Allocation Tracker to get a better understanding of
where your memory-hogging objects are allocated. The Allocation Tracker can be useful not only for looking at specific
uses of memory, but also to analyze critical code paths in an app such as scrolling.
For example, tracking allocations when flinging a list in your app allows you to see all the allocations that need to be done
for that behavior, what thread they are on, and where they came from. This is extremely valuable for tightening up these
paths to reduce the work they need and improve the overall smoothness of the UI.
85

To use Allocation Tracker:


1. Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
2. In the DDMS window, select your app's process in the left-side panel.
3. In the right-side panel, select the Allocation Tracker tab.
4. Click Start Tracking.
5. Interact with your app to execute the code paths you want to analyze.
6. Click Get Allocations every time you want to update the list of allocations.
The list shows all recent allocations, currently limited by a 512-entry ring buffer. Click on a line to see the stack trace that
led to the allocation. The trace shows you not only what type of object was allocated, but also in which thread, in which
class, in which file and at which line.

86

Figure 2. The Device Monitor tool, showing recent app allocations and stack traces in the Allocation Tracker.
Viewing Overall Memory Allocations

For further analysis, you may want to observe how your app's memory is divided between different types of RAM
allocation with the following adb command:
adb shell dumpsys meminfo <package_name>
The output lists all of your app's current allocations, measured in kilobytes.
87

Capturing a Heap Dump

A heap dump is a snapshot of all the objects in your app's heap, stored in a binary format called HPROF. Your app's heap
dump provides information about the overall state of your app's heap so you can track down problems you might have
identified while viewing heap updates.
To retrieve your heap dump:
1. Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
2. In the DDMS window, select your app's process in the left-side panel.
3. Click Dump HPROF file, shown in figure 3.
4. In the window that appears, name your HPROF file, select the save location, then click Save.

Figure . The Device Monitor tool, showing the [1] Dump HPROF file button.
88

Using the Eclipse Memory Analyzer Tool


The Eclipse Memory Analyzer Tool (MAT) is just one tool that you can use to analyze your heap dump. It's also quite
powerful so most of its capabilities are beyond the scope of this document, but here are a few tips to get you started.
Once you open your converted HPROF file in MAT, you'll see a pie chart in the Overview, showing what your largest
objects are. Below this chart, are links to couple of useful features:

The Histogram view shows a list of all classes and how many instances there are of each.
You might want to use this view to find extra instances of classes for which you know there should be only a certain
number. For example, a common source of leaks is additional instance of your Activity class, for which you should
usually have only one instance at a time. To find a specific class instance, type the class name into the <Regex> field at
the top of the list.
When you find a class with too many instances, right-click it and select List objects > with incoming references. In the
list that appears, you can determine where an instance is retained by right-clicking it and selecting Path To GC
Roots >exclude weak references.
The Dominator tree shows a list of objects organized by the amount of retained heap.
What you should look for is anything that's retaining a portion of heap that's roughly equivalent to the memory size you
observed leaking from the GC logs, heap updates, or allocation tracker.
When you see something suspicious, right-click on the item and select Path To GC Roots > exclude weak references.
This opens a new tab that traces the references to that object which is causing the alleged leak.
Note: Most apps will show an instance of Resources near the top with a good chunk of heap, but this is usually expected
when your app uses lots of resources from your res/ directory.

89

Figure . The Eclipse Memory Analyzer Tool (MAT), showing the Histogram view and a search for "MainActivity".

Comparing heap dumps


You may find it useful to compare your app's heap state at two different points in time in order to inspect the changes in
memory allocation. To compare two heap dumps using MAT:
1. Create two HPROF files as described above, in Capturing a Heap Dump.
2. Open the first HPROF file in MAT (File > Open Heap Dump).
3. In the Navigation History view (if not visible, select Window > Navigation History), right-click on Histogram and
selectAdd to Compare Basket.
4. Open the second HPROF file and repeat steps 2 and 3.
5. Switch to the Compare Basket view and click Compare the Results (the red "!" icon in the top-right corner of the view).
90

Triggering Memory Leaks

While using the tools described above, you should aggressively stress your app code and try forcing memory leaks. One
way to provoke memory leaks in your app is to let it run for a while before inspecting the heap. Leaks will trickle up to the
top of the allocations in the heap. However, the smaller the leak, the longer you need to run the app in order to see it.
You can also trigger a memory leak in one of the following ways:
1. Rotate the device from portrait to landscape and back again multiple times while in different activity states. Rotating the
device can often cause an app to leak objects because the system recreates them and if your app holds a reference to one
of those objects somewhere else, the system can't garbage collect it.
2. Switch between your app and another app while in different activity states (navigate to the Home screen, then return to
your app).

91

Opera Mobile Emulator for desktop

92

Figure 1: Opera Mobile Emulator running on Mac.

Introduction
Making sure that your site looks great and works exactly as it should in mobile and tablet browsers can often be a tedious
process you typically need one or more physical devices, or some form of virtual machine emulating the whole operating
system, and thats just the start.
Opera Mobile Emulator for Windows, Linux and Mac makes things a whole lot easier.
Its a small, native application thats easy to install on your desktop machine and runs exactly the same code as its mobile
phone version that way, you can be assured that what youre seeing on your test environment is practically identical to the
experience your end users will get.

The Profile Selector


When you first open the Opera Mobile Emulator, youre presented with the Profile Selector see Figure 2. This Profile
Selector allows you to spawn different instances of Opera Mobile on your desktop to accurately test different phone
configurations, as seen in Figure 3. Here we will discuss the different options available in the Profile Selector.
Profiles
The Profile Selector comes preconfigured with a series of popular phone and tablet device profiles, such as Samsung Galaxy S

III,Samsung Galaxy Tab 10.1 and HTC One X. You can then start an Opera Mobile instance using the selected profile by
clicking on the Launch button.
93

If you want to create a new profile, select the Custom option from the profile list and set the relevant options
forResolution, Pixel Density, User Interface, User Agent String, Window Scale, and Arguments. When you're all set, select
the Add button under the profile selection box, choose a name for the new profile, and save it to the list. Note that you can
also tweak existing profiles via the Save/save as... button appearing below the selected profile, or delete them using
the Remove button.

94

Figure 2: The Opera Mobile Emulators Profile Selector.

Resolution
Mobile phones and tablets come in varying shapes and sizes. The screen resolution can be changed by choosing between the
different options in the Resolution dropdown menu. You can also create your own custom resolutions using the Add button,
and delete the existing ones using the Remove button.
Pixel Density
In the same manner as screen resolution, you can choose the pixel density which affects Opera Mobile's default zoom
factor and devicePixelRatio using the dropdown menu in the Pixel Density section. As above, you can select options from the
menu, add your own custom ones, and remove options as you see fit.
User Interface
The User Interface section of the Profile Selector contains a dropdown menu with three options to choose
from:Touch, Keypad and Tablet. The Touch option will give you our touch-screen phone UI, whereas choosing Keypadwill
result in our UI for phones with only keypad input. The Tablet option enables Opera Mobiles tablet-optimized touch UI. To
learn more about the differences between these UIs and input modes they trigger, see the input modes section below.

95

Figure 3: Multiple instances of the Opera Mobile Emulator with different screen sizes, orientations, and UIs.

96

User Agent String


This option allows you to set a custom User Agent before launching an Opera Mobile instance. Available options
are Default (Opera Mobi on Win/Mac/Linux), Android (Opera Mobi on Android), MeeGo (Opera Mobi on MeeGo), Desktop (Opera
Desktop).
When running in tablet mode, the UA string is slightly different: Opera Mobi is replaced with Opera Tablet, so as to avoid that
sites that use browser-sniffing send a mobile/small-screen optimised version to a large-screen tablet device.
If you need to set a totally custom UA string, then this can be done as well: launch Opera Mobile with any UA string setting,
open opera:config, search for the Custom User-Agent property in the User Prefs section, give it your preferred UA string value
and save. To revert to the default value, simply click the Default or Reset button.
Window Scale

Window Scale allows you to display the full browser window at a percentage of its original size. This is useful when the
spawned Opera Mobile instance has a larger height than the height of your computer screen and you want to make it fit
inside: e.g. the HTC One X profile triggers Opera Mobile to have a size of 7201280px in portrait orientation, which is too tall
to fit on my Dell monitor. The Profile Selector knows this and therefor launches the HTC One X Opera Mobile instance at 50%
of its original size, while preserving the reported width, height, anddevicePixelRatio values.
If you want to change the Window Scale value after launching, you can do this as well through the dropdown menu in the
bottom right corner of the Opera Mobile instance.

97

Arguments
The Arguments field allows you to add various command line options to the Opera Mobile instance youre launching. You can
find an overview of the available arguments by clicking Help on the Profile Selector.
Some example arguments:

-displayzoom percentage: this allows you set any arbitrary window scale factor.

-delaycorethread delay: this allows you to delay each message in the Presto thread by a certain amount of ms, so as to emulate a slow

device.

-url url: define a URL to open on startup.

Full browser reset on startup


Checking this box will reset all browser settings when Opera Mobile is launched, including cache, cookies, and so on.

Launching Opera Mobile instances from the command line


Depending on your workflow, you may want to start Opera Mobile instances from the command line, bypassing the Profile
Selector. That is entirely possible, with various configuration options to boot. The most important ones are:

-displaysize widthxheight: set the window size

-ppi ppi: set the pixel density you want to use

-notouch: start Opera Mobile with Keypad UI

-user-agent-string uastring: set the user agent option to the specified value. Options are: Default, Android, MeeGo, Desktop.

-notouchwithtouchevents: same as -notouch, but its still possible to use the mouse for easier debugging

-tabletui: switch to the tablet UI

98

Note: For a full list of command-line arguments, see the applications help text with operamobile --help.

So, if we wanted to run Opera Mobile as a keypad device with an FWVGA-sized screen in portrait orientation, wed use the
following commands:

On Windows: OperaMobileEmu.exe -displaysize 854x480 -notouch

On Linux: operamobile -displaysize 854x480 -notouch

On Mac: ./Opera\ Mobile -displaysize 854x480 -notouch

The default location of the Opera Mobile Emulator's executable will depend on your operating system. By default, you should
find it here:

Windows: C:\Program Files\Opera Mobile Emulator\

Linux: /usr/bin/

Mac: /Applications/Opera Mobile Emulator.app/Contents/Resources/Opera Mobile.app/Contents/MacOS/

Input modes: touch, keypad and tablet


In the Touch and Tablet User Interface, you use the mouse as if it was a finger on an actual touch-screen device. A short click
activates links and controls, double-click zooms in and out of a page, while clicking for more than a second (tap-and-hold)
brings up the context menu. Scrolling is achieved by clicking and dragging.
Any text entry field (such as form elements in a web page, or the browser's own address bar) will trigger an emulated onscreen keyboard, but you can of course use your regular keyboard for convenience. If youd like to suppress the virtual
keyboard (to simulate a mobile device with its own physical keyboard), use F6 to toggle it on/off.

99

Emulating pinch zoom is also possible: simply scroll the mouse-wheel while holding CTRL (Windows and Linux) or (Mac). On
Mac OS X 10.6 and above, you can even use the pinch zoom gesture on the trackpad.
In Keypad input mode, the primary controls are:

Cursor keys can be used for spatial navigation around the Speed Dial, address bar and search field. On a web page, the cursor keys
move the virtual mouse pointer.

F1 and F2 map to the top left and right soft keys, which activate the functions at the bottom of the screen.

Enter can be used to activate a control, zoom into the page, etc.

For your debugging convenience, the Keypad input mode comes with mouse interaction enabled by default (in other words, notouchwithtouchevents

is the default), allowing you to click on the different UI and page elements. If you prefer the emulator to

just respond to keyboard input, you can add a -notouch argument when initiating an Opera Mobile instance from the Profile
Selector.
In all input modes, ALT / + R is used to simulate a device rotation (or you can click the Rotate screen button in the info bar
at the bottom), switching between portrait and landscape mode. F5 or CTRL / + R on the other hand reload the current
page.
Also note that in all modes you can perform select all, cut, copy and paste actions using the standard OS clipboard and
shortcut keys. In addition, CTRL / + E allows you to open the last string copied to the clipboard as a URL in a new tab. You
can also use TAB and SHIFT+TAB to navigate between form elements and backspace to go to the previous page.

Features and settings of the browser

100

In general usage, Opera Mobile Emulator offers the same functionality available on mobile phones and tablets, including
integration of Opera Turbo and Opera Link, which allows you to sync your bookmarks with our Opera Link servers and other
Opera instances.

Figure 4: Changing settings in the Opera Mobile Emulator.

101

As with Opera Mobile running on devices, the Settings (Figure 4) give quick access to toggle various features and,
under Privacy, to clear the history, passwords, cookies, cache and shared locations.
Power-users can enter opera:config into the address bar for complete access to all configuration options.

102

S-ar putea să vă placă și