You are on page 1of 93

QUALITY THOUGHT QTP-MATERIAL

Page 1 of 93

Introduction to Automation Testing
1. What is Automation?
2. Why we Need to go for Automation?
3. When we Need to go for Automation?
4. When not to go for Automation?
What is Automation?
Test Automation is the process of simulating a set of (manual) actions on the given system
using an Automation tool or utility
REMEMBER:
Automation is NOT a replacement for manual testing
Automation is NOT intended to find bugs
100% testing cant be automated
Why to Automate:
Repetitive tests performed by a tester manually
May result in Human Errors
Consume more time
Automation Helps to
Reducing repetitive manual interactions with system during testing phase
Improve product reliability & quality by eliminating human errors
Improve Test Coverage with automation, and
Reduce costs of testing [when wisely used]
What to Automate:
Tests that Need to Run for Every Build
Tests that use multiple data values for same action
Identical tests that need to be executed using different browsers
What NOT to Automate:
Tests Cases that will only be executed once
Test Cases used for Ad-hoc/random Testing
Test cases that are infrequently selected for execution
Test cases that will require manual intervention i.e. a task not possible to automate
The most important one-based on the intuition and knowledge of application
E.g. If you find that you cant escape from manual intervention



QUALITY THOUGHT QTP-MATERIAL

Page 2 of 93

Advantages of Automations:
Less Execution Time and Effort. Tests can be executed on unattended mode and 24*7.
Parameterize all the input data through a single global data sheet makes it easy to modify the
input data for any future enhancement in the application thus reducing the maintenance cost.
Automation is cost effective.
QTP Testing Process:
Test Planning
Plan How you want to automate your Tests
Creating Tests
Recording steps using QTP
Coding steps
Enhancing your test
Insert Checkpoints
Parameterization
Debugging your test
Ensure that it operates smoothly and without interruption
Running your test
Run the test to check the behavior of your application
Analyzing the Test results
Examine the test results to locate defects in your application
Reporting defects
Report the defects in to bug tracking tool
QUALITY THOUGHT QTP-MATERIAL

Page 3 of 93






QUALITY THOUGHT QTP-MATERIAL

Page 4 of 93

QTP Tool Features
QTP was Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007
QTP is an Object Based Testing Tool
QTP is for Functional and Regression Testing
It follows Keyword Driven Approach
It supports Windows Operating Environment only.
It supports GUI based (Graphical user interface) and Web based Applications Automation,
does not support CUI (Command user interface) Applications.
It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages
with respect to license.)
It has adapted Microsoft Visual Basic Scripting edition for programming and Excel like
spread sheet for Data driven testing.
Tools support for QTP:
VB Script for Scripting (for implementing programming logic)
VB Script Engine integrated in QTP, so apart from scripting features we can use File system,
Excel, word, Adodb etc. Object models from QTP.
SQL (Structured query language) Engine integrated in QTP, so we can use SQL Statements in
QTP to perform Database Operations
Excel like spread sheet integrated in QTP for performing Data driven Testing
We can install MS Script Debugger with QTP for Debugging Test scripts.
QTP uses XML format for Test results, Environment variables and for exporting object
repositories.
QTP can be integrated with other Tools like WinRunner and Quality Center.
QTP can be used for user interface (UI) test case automation and some limited (Non UI) Test case
automation like File system operations and Data base operations.
It was derived from Astra QuickTest (mother tool of QTP).
It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers
like Mozilla and AOL, opera Etc apart from IE.
QTP is a Desktop Application (I-Tier/Stand alone).
QTP developed in .NET Technology.
Since it is Stand-alone Application, It doesn't have Database, It stores resources as files (Internal
and External). We can't share qtp services from one machine to another, but we can share
resources (Ex: Object Repository files, Function Libraries, Environment variable files, Recovery
scenario files etc...)


QTP has two types of License:
Seat or Node locked License
Concurrent or float license.
We have to use Seat license from fixed system/machine and Concurrent License, we can
use from any system but one user at a time. If we want multiple concurrent licenses that
we can purchase
QTP has UNI code support.
Version History of QuickTest Professional
QUALITY THOUGHT QTP-MATERIAL

Page 5 of 93

Astra QuickTest (Mother tool of QTP) 1.0 to 5.0
QTP derived from Astra QuickTest and influenced by WinRunner
Quick Test Professional
5.6 Nov 2002
6.5 2003
8.0 2004
8.2, 8.3 2005
9.0,9.1-2006
9.2- 2007 Mercury Interactive
9.5 2008 H.P
10.00 2009 January
11.00 2010** (It is Latest Version)
********************************************
QTP Tool Window Menus

QTP Commands are available in 3 ways.
1. Menu options
2. Tool Bar options
3. Short cut keys (for Some important operations only)
File menu: Through file menu user can create, save tests, open existing tests, export tests in zip format.

Command Function
New > Test Creates a new test. Ctrl+N
New > Business Component Creates a new business component. Ctrl+Shift+N
New > Scripted Component Creates a new scripted component.
New > Application Area Creates a new application area. Ctrl+Alt+N
New > Function Library Creates a new function library. Shift+Alt+N
Open > Test Opens an existing test. Ctrl+O
Open > Business/Scripted
Component
Opens an existing business or scripted
component.
Ctrl+Shift+O
Open > Application Area Opens an existing application area. Ctrl+Alt+O
Open > Function Library Opens an existing function library. Shift+Alt+O
Close Closes the active function library.
Close All Function Libraries Closes all open function libraries.
Quality Center Connection Opens the Quality Center Connection dialog
box, enabling you to connect to a Quality Center
project.

Quality Center Version
Control
Provides a sub-menu of options for managing
versions of QuickTest assets in Quality Center.
The sub-menu is available only when you are
connected to version-control enabled
Quality Center project.

Save Saves the active document. Ctrl+S
Save As Opens the relevant Save dialog box so you can
save the open document.

Save Test with Resources Saves a standalone copy of the current test
together with its resource files.

Save All Saves all open documents.
Enable Editing Makes read-only function libraries editable.
QUALITY THOUGHT QTP-MATERIAL

Page 6 of 93

Export Test to Zip File Creates a zip file of the active document. Ctrl+Alt+S
Import Test from Zip File Imports a document from a zip file. Ctrl+Alt+M
Convert to Scripted
Component
Converts a business component to a scripted
component.
Ctrl+Alt+C
Print Prints the active document. Ctrl+P
Print Preview Displays the Keyword View as it will look
when printed and enables you to modify the
page setup.

Settings Opens the Settings dialog box, enabling you to
define settings for the open document. (Not
relevant for function libraries)

Process Guidance
Management
Opens the Process Guidance Management
dialog box, enabling you to manage the list of
processes that are available in QuickTest.

Associate Library
'<Function Library Name>'
with '<Document Name>'
Associates the active function library with the
open document. (Available only from function
libraries)

Recent Files Lists the recently viewed files.
Exit Closes the QuickTest session.


Edit Menu: It provides editing options and renaming, deleting and splitting actions.


Command Function
Undo Reverses the last command or deletes the last entry
you typed.
Redo Reverses the most recent operation of the Undo
command.
Cut Removes the selection from your document.
Copy Copies the selection from your document.
Paste Pastes the selection to your document.
Delete Deletes the selection from your document.
Copy Documentation to
Clipboard
Copies the content of the Documentation column of
the Keyword View, enabling you to paste it in an
external application.
Action > Split Action Separates an action into two sibling actions or into
parent-child nested actions.
Action > Rename Action Changes the name of an action.
Action > Delete Action Enables you to remove the selected call to the action,
or delete the action and its calls from the active test.
Action > Action Properties Enables you to specify options, parameters, and
QUALITY THOUGHT QTP-MATERIAL

Page 7 of 93

associated object repositories for a stored action.
Action > Action Call
Properties
Enables you to specify the number of run iterations
according to the number of rows in the Data Table,
and to define the values of input parameters and the
storage location of output parameters.
Step Properties > Comment
Properties
Opens the Comment Properties dialog box for a
comment step. Available only when the selected step
is a comment.
Step Properties > Object
Properties
Opens the Object Properties dialog box for a selected
object. Available only when the selected step contains
a test object.
Step Properties > Checkpoint
Properties
Opens the relevant Checkpoint Properties dialog box
for a selected object. Available only when the selected
step is a checkpoint step.
Step Properties > Output
Value Properties
Opens the relevant Output Value Properties dialog box
for a selected object. Available only when the selected
step is an output value step.
Step Properties > Report
Properties
Displays the Report Properties dialog box for a report
step. Available only when the selected step is a
Reporter.ReportEvent step.
Find Searches for a specified string.
Replace Searches and replaces a specified string.
Go To Moves the cursor to a particular line in the test.
Bookmarks Creates bookmarks in your script for easy navigation.
Advanced > Comment Block Comments out the current row, or selected rows.
Advanced > Uncomment
Block
Removes the comment formatting from the current or
selected rows.
Advanced > Indent Indents the step according to the tab spacing defined in
the Editor Options dialog box.
Advanced > Outdent Outdents the step (reduces the indentation) according
to the tab spacing defined in the Editor Options dialog
box.
Advanced > Go to Function
Definition
Navigates to the definition of the selected function.
Advanced > Complete Word Completes the word when you type the beginning of a
VBScript method or object.
Advanced > Argument Info Displays the syntax of a method.
QUALITY THOUGHT QTP-MATERIAL

Page 8 of 93

Advanced > Apply "With" to
Script
Generates With statements for the action displayed in
the Expert View, and enables IntelliSense within With
statements.
Advanced > Remove "With"
Statements
Converts any With statements in the action displayed
in the Expert View to regular (single-line) VBScript
statements.
Optional Step Inserts an optional step (a step that is not required to
successfully complete a run session).



View menu: Through this menu we can launch and close, active screen, Data Table, Debug viewer,
information, missing resources etc.
Test Pane:
It is programming interface of QTP, used for creating, editing, viewing and deleting test scripts.

Test: It is a set of statements or set of one or more actions. (It is a local concept)

Action: It is a set of Statements. (It is a local concept)

Statement: A minimal executable unit. Statements may have keywords. (Keyword such as function,
method, statement etc). It is a global concept.


Test pane has 2 views.

Expert view- Test in VB script format.
Key word view- Test in Icon based GUI format.
QUALITY THOUGHT QTP-MATERIAL

Page 9 of 93



Note1: Here in test pane Test is same but views are different, if you perform any modifications in one
view those automatically reflects in another view.

Note 2: Technical users use expert view and business user use key word view.

Note 3: User can customize Test pane view options.

Navigation: Tools Menu> view options> we can use font size and colors etc.

2) Active Screen
It has an optional element of QTP, it takes snap shots of every statement that user performed action or
operation on AUT.

It can be used for understanding and editing the test easily.

Navigation: View menu>active screen (for launching and closing)


Configuring Active Screen: Tools > Options > Active screen tab > Increase / Decrease capture level,
Apply and OK.
QUALITY THOUGHT QTP-MATERIAL

Page 10 of 93


Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP.

3) Data Table
It has an integrated spread sheet (Excel like), used for Data driven testing.

Navigation: View menu>Data table (for launching and closing)


Data driven Testing: Testing the same task(S) or same operation with multiple sets of test data.

It can be used in two ways.

1. Enter test data directly into Data Table and use.

2. Importing data from external files (Flat files, excel sheets, etc) and Data bases (MS access, Sql Server,
oracle, etc.)

It has two types of sheets.

1). Global Sheet- for entire Test /used for all actions in the Test.
2). Action Sheets- for specific Action only.

Data table available in 2 ways:

1). Design time data table. (Attached with every test)
2). Run time data table. (Available in result window)

Run time is a carbon copy of design time data table.
QTP has Data table methods for performing operations on data table.
QUALITY THOUGHT QTP-MATERIAL

Page 11 of 93


4) Debug Viewer
It is used for locating and rectifying or fixing errors.
It can be used for debugging the tests by step-by-step execution.

We use Step into, Step over and Step out commands for debugging. (debug commands)

Navigation: View menu>debug viewer (for launching and closing)



Through Debug viewer user can watch variables and change values of variables temporarily.

5) Missing Resources

It can be used for showing missing resources that attached to current test such as (Recovery Scenarios,
Library files etc).

Navigation: View menu >missing resources (for launching and closing)

6) Information
This pane shows syntax errors automatically during saving the test.
Navigation: view menu> information
QUALITY THOUGHT QTP-MATERIAL

Page 12 of 93



Insert Menu: Through this menu user can inserting check points, out put values, synchronizing points.
In this menu step generator available, using this user can generate recordable and non-recordable scripts.

Through insert menu user can insert VB Script conditional and loop statements and transaction points
(Start and End).

Through insert menu user can create new actions, call existing actions and copy existing actions.

Automation Menu:
This menu provides Record, Run options and Run setting options
Through this menu we can start normal recording, analog recording and Low level recording.

Through this menu we can stop recoding, running and also we run tests.

Command Function Short Cut
Keys
Record Starts a recording session. F3
Run Starts a run session from the beginning or from
the line at which the session was paused.
F5
Stop Stops the recording or run session. F4
Run Current Action Runs only the active action.
Run from Step Starts a run session from the selected step. Ctrl+F5
Maintenance Run Mode Starts a run session during which the
Maintenance Run Mode wizard opens for steps
that failed because an object was not found in the
application (if applicable).

Update Run Mode Starts a run session to update test object
descriptions and other options (if applicable).

Analog Recording Starts recording in Analog Recording mode. Shift+Alt+F3
Low Level Recording Starts recording in Low Level Recording mode. Ctrl+Shift+F3
Record and Run Settings Opens the Record and Run Settings dialog box,
QUALITY THOUGHT QTP-MATERIAL

Page 13 of 93

enabling you to define browser preferences for
recording and running your test.
Process Guidance List Lists the processes that are available for the
current document type and for the currently
loaded QuickTest add-ins, enabling you to open
them.

Results Enables you to view results for a test run session.
QTP supports three types of recording modes. They are:
1) Normal recording mode
2) Analog Recording
3) Low Level Recording
1) Normal recording mode records the objects in your application and the operations performed on them.
This mode is the default and takes full advantage of the QuickTest test object model, recognizing the
objects in your application regardless of their location on the screen.
2) Analog Recording. Enables you to record the exact mouse and keyboard operations you perform in
relation to either the screen or the application window. In this recording mode, QuickTest records and
tracks every movement of the mouse as you drag the mouse around a screen or window.
3) Low Level Recording. Enables you to record on any object in your application, whether or not
QuickTest recognizes the specific object or the specific operation. This mode records at the object level
and records all run-time objects as Window or WinObject test objects. Use low-level recording for
recording in an environment or on an object not recognized by QuickTest. You can also use low-level
recording if the exact coordinates of the object are important for your test.
Resources Menu:
This menu provides object repository and recovery scenarios options.
Through this menu we can create /modify/delete objects information and we can associate repositories.
Through this menu we can create, modify and delete recovery scenarios.

Command Function
Object Repository (Ctrl+R) Opens the Object Repository window, which displays
a tree containing all objects in the current test or
component.
Object Repository Manager Opens the Object Repository Manager dialog box,
enabling you to open and modify multiple shared
object repositories.
Associate Repositories Opens the Associate Repositories dialog box, enabling
you to manage the object repository associations for
the test.
Map Repository Parameters Opens the Map Repository Parameters dialog box,
enabling you to map repository parameters, as needed.
Recovery Scenario Manager Opens the Recovery Scenario Manager dialog box.
Associated Function
Libraries
Lists the function libraries associated with the active
document, enabling you to open them.

Debug Menu:
QUALITY THOUGHT QTP-MATERIAL

Page 14 of 93

This menu provides debug commands for step by step execution.
Through this menu we can insert/remove/break points.

Tools Menu:
This menu provides Tools settings option, view options and object identification configuration.
Through this menu we can set tool options as well as test pane view options.
In this menu object spy option available, through this we can get objects information.(Properties and
values)
In this menu Virtual object option available; through this option we can create virtual objects.

Command Function
Options Opens the Options dialog box, enabling you to modify global
testing options.
View Options Opens the Editor Options dialog box, enabling you to customize
how tests and function libraries are displayed in the Expert View
and Function Library windows.
Check Syntax (Ctrl+F7) Checks the syntax of the active document.
Object Identification Opens the Object Identification dialog box, enabling you to
specify how QuickTest identifies a particular test object.
Object Spy Opens the Object Spy dialog box, enabling you to view the native
properties and operations of any object in an open application, as
well as the test object hierarchy, identification properties, and
operations of the test object that QuickTest uses to represent that
object.
Web Event Recording
Configuration
Opens the Web Event Recording Configuration dialog box,
enabling you to specify a recording configuration level. (Relevant
for tests only)
Data Driver Opens the Data Driver dialog box, which displays the default
Constants list for the action. (Relevant for tests only)
Change Active Screen Replaces the previously recorded Active Screen with the selected
Active Screen. (Relevant for tests only)
Virtual Objects > New
Virtual Object
Opens the Virtual Object Wizard, enabling you to teach
QuickTest to recognize an area of your application as a standard
test object.
Virtual Objects > Virtual
Object Manager
Opens the Virtual object Manager, enabling you to manage all of
the virtual object collections defined on your computer.
Customize Opens the Customize dialog box, which enables you to customize
toolbars and menus, and create new menus.

Window Menu:
This menu provides QTP tool window style settings.

Help Menu:
This menu provides QTP help as well as VB Script help.
Through this menu we can contact technical support people and we can send feedback.
Through this menu we can check for updates and download or install directly.




QUALITY THOUGHT QTP-MATERIAL

Page 15 of 93


Object Identification Configuration

Object:
Object is something, which has structure and properties.
Every test automation tool is GUI (graphical user interface) sensitive. Test automation tool has to identify
the objects on the application, then only it can do the intended operations.
Quick Test Professional has its own mechanism to identify the objects on the Application under Test.
QTP has various add-ins available for different applications.

Let us have a look at the QTPs object identification mechanism
1. Open QTP
2. Click Tools > Object Identification
3. Object Identification dialog gets opened



QUALITY THOUGHT QTP-MATERIAL

Page 16 of 93

In QTP 10.0 standard installation, it comes with ActiveX, Visual Basic, and Web add-ins and can identify
the objects of ActiveX, Standard Windows, Visual Basic, and Web applications.
QTP identifies the objects with the following properties:
1. Mandatory properties
2. Assistive properties
3. Smart identification
4. Ordinal identifier
o Location
o Index

Will get into each one of these bullet points later. Let us have look at one of the important features of
QTP which will be used many times during the test automation of an application is Object Spy.
Open the Application under Test (AUT)
Click Tools > Object Spy..


QUALITY THOUGHT QTP-MATERIAL

Page 17 of 93

Click on the hand button on the spy
Click on a particular object on the AUTs user interface.
All the properties of the object will be displayed on this spy.
Below figures illustrate how object spy displays the object properties (Windows, Visual Basic,
and Web application are taken as examples)


Types of Object in QTP:
There are four types of object available in QTP.
1. Run time objects
2. Test objects
3. Utility objects
4. Automation objects/User defined objects.

Run time objects: The objects present in the AUT. Ex: Buttons, Links, etc

Test Objects: References of Run time objects. Ex: WinEdit, WinButton, WebButton, Link, etc

Note:
Test objects names vary from one environment to another.

Utility objects

They are QTP reserved objects used for Testing and Result reporting.

Ex:
1. SystemUtil for launching/closing the application.
2. Reporter for defining results.
3. Services for inserting transaction points
4. Environment for using environment variables



QUALITY THOUGHT QTP-MATERIAL

Page 18 of 93






1) Systemutil:
Operating System












From the above diagram, It is Clearly understood that the Browser, Notepad, Car Game anything
installed in windows are all SIBLINGS under the windows operating system. To access these installed
application, we need to have reference of the operating system-----
SystemUtil will give you the reference of the operating system
Systemutil:
Is an implicit object of QTP that brings reference to existing operating system in which QTP is installed
instantly
Example:
Suppose QTP is installed in windows 7 operating system then systemutil bring the reference of
windoews7 operating system
Methods:

BlockInput
Prevents Keyboard and mouse input events from reaching
application
CloseDescendentProcesses Closes all processes by Quick Test
CloseProcessByHwnd Closes a process that is the owner of a window with the specified
handle
CloseProcessById Closes a process according to its process ID (PID)
CloseProcessByName Closes a process according to its name
CloseProcessByWndTitle Closes all processes that are owners of windows with the specified
title
Run Runs a file or Application
UnblockInput Re-enables Keyword and mouse input events after a BlockInput
statement was used to Block them

Process Names that we use in Above Methods
Application Name Windows Process name
Notepad Notepad.exe
Wordpad Winword.exe
Internet Explorer Iexplore.exe
BROWSER
PPTS
NOTEPAD
CARGAMES
PAGE
OBJECTS in
BROWSER
QUALITY THOUGHT QTP-MATERIAL

Page 19 of 93

Micro soft paint Mspaint.exe
Excel Excel.exe
Filght "C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight4a.exe"

2) Reporter:
The object used for sending information to the test results
Syntax:
Reporter.ReportEvent EventStatus, ReportStepName, Details [, ImageFilePath]
Argument Type Description
EventStatus Number or
pre-defined
constant
Status of the Test Results step:
0 or micPass: Causes the status of this step to be passed and sends
the specified message to the Test Results window.
1 or micFail: Causes the status of this step to be failed and sends the
specified message to the Test Results window. When this step runs,
the test fails.
2 or micDone: Sends a message to the Test Results window without
affecting the pass/fail status of the test.
3 or micWarning: Sends a warning message to the Test Results
window, but does not cause the test to stop running, and does not
affect the pass/fail status of the test.
ReportStepName String Name of the step displayed in the Test Results window.
Details String Description of the Test Results event. The string will be displayed in
the step details frame in the Test Results window.
ImageFilePath String Optional. Path and filename of the image to be displayed in the
Results Details tab of the Test Results window. Images in the
following formats can be displayed: BMP, PNG, JPEG, and GIF.
Notes:
Images cannot be loaded from Quality Center.
Including large images in the test results may impact
performance.
If an image is specified as a relative path, QuickTest will
first search the Results folder for the image and then the
search paths specified in the Folders pane of the Options
dialog box.

Example:
The following examples use the ReportEvent method to report a failed step.
Reporter.ReportEvent 1, "Custom Step", "The user-defined step failed."
or
Reporter.ReportEvent micFail, "Custom Step", "The user-defined step failed."
The following example uses the ReportEvent method to include a captured bitmap in the test
results.
Browser("Browser").Page("WebPage").Image("MyLogo").CaptureBitmap("MyLogo.bmp")
Reporter.ReportEvent micDone, "Display Logo", "This is my logo", "MyLogo.bmp"

3) Environment:
Enables you to work with environment variables.
QUALITY THOUGHT QTP-MATERIAL

Page 20 of 93

You can set or retrieve the value of environment variables using the Environment object. You can
retrieve the value of any environment variable. You can set the value of only user-defined,
environment variables.



Syntax :
To set the value of a user-defined, environment variable:
Environment (VariableName) = NewValue
To retrieve the value of a loaded environment variable:
CurrValue = Environment (VariableName)
Argument Type Description
VariableName String The name of the environment variable.
NewValue Variant The new value of the environment variable.
CurrValue Variant The current value of the environment variable.
Example
The following example creates a new internal user-defined variable named MyVariable with a value
of 10, and then retrieves the variable value and stores it in the MyValue variable.
Environment.Value("MyVariable")=10
MyValue=Environment.Value("MyVariable")

Automation objects/User defined objects

User can create objects; those can be used for performing specific operations. Ex: Creating objects in
filesystemobject class, adodb.connection class, and dictionary object class, Excel. Application class etc


Overview:
Generally for every object 20-25 properties information available, qtp recognizes object using 2 0r 3
important properties.

Qtp has default object identification configuration for every environment, if we feel that config is not
sufficient for recognizing objects in our application, we can configure some more

Object Identification Types:

a) Normal identification
Mandatory properties
Assistive properties

b) Smart identification
base filter properties
optional filter properties
c) Ordinal identifier
Location
QUALITY THOUGHT QTP-MATERIAL

Page 21 of 93

Index
creation time(only for web)


QTP learns information in the following in case of normal identification:

First of all the qtp learns all the mandatory properties at a time and thinks whether these properties
sufficient to identify the object uniquely. if it feels sufficient then it stops learning otherwise,
It learns first assistive property and once again stops and thinks, like this qtp learns one by one. At the end
of assistive properties list also if it feels not satisfied and it finally goes to Ordinal Identifier.

QTP learns information in the following in case of Smart Identification:

Smart identification is an optional feature, if we feel normal identification is not sufficient for any object,
and then we configure Smart Identification for that object, in order to avoid Ordinal Identifier.

After normal identification if qtp feels not satisfied then it goes to smart identification.
In smart identification 2 types of properties available, first qtp learns all base filter properties at a time
and thinks whether these properties are sufficient for identifying the object uniquely. If it feels sufficient,
then it stops learning otherwise it goes Optional Filter Properties and learns one by one. Still it feels not
satisfied finally it goes to Ordinal Identifier.

Ordinal identifiers:
There are 3 types of ordinal identifiers available
1) Location: is based on object location in the AUT, location starts from zero.
2) Index: it is based on sequence of the programs, index starts from zero
3) Creation time: it is based on loading time of the web objects. QTP generates 0,1,2 like
numbers.
Tool Settings Globalization:
As QTP is a I-tier(Stand-alone) application, making Tool settings globally is not possible.
or making tool settings global, QTP is providing a special feature called "Generate Script".
STEPS:
1) Settings available in 3 areas
a) File->Settings
b) Tools->Options
c) Tools->Object Identification
2) Perform required settings and generate Scripts
3) Share Script files to team members and ask them to execute those scripts.
NOTE: After executing these scripts all team members can get same settings.

Object Repository

Object Repository:

It is a storage place of QTP where objects information can be stored and it also acts as interface between
the Test script and the AUT in order to identify the objects during execution.
There are two types of repository available in QTP.
1) Local repository (.MTR extension)
2) Shared repository(.TSR extension)
Local Repository:
QUALITY THOUGHT QTP-MATERIAL

Page 22 of 93

QTP creates a Local Repository for every Action automatically during Recording. That cannot be
shared among tests.
User can add some more objects to Local repository
User can perform rename, delete operations on local repository. As it is QTP internal file user no
need to save modifications.

Shared Repository:
User (Test Engineer) creates the Shared Repository by adding objects. That can be shared among
number of tests.
Using this method user can perform modifications on objects easily.

Operations on Object Repository

Adding objects

a) Local Repository:
Navigation: open Local Repository (Resource Menu > Object Repository)
objects>Add objects to Local> Show the Object>Click Ok
(No need to save separately, it saves automatically)
b) Shared Repository:
Navigation: Resource menu>object repository manager>object>Add objects>show the
window/object>click ok
Selected object only
Default object types
All objects types
Selected object types
(If we select first option it stores selected objects only, if we select second option it stores
all default objects, if we select third option it stores All objects including static objects, if
we select fourth option, we have to select object classes then it stores that class objects,
we can select more than one class also.)
Renaming Objects
a) Local Repository:
Resources > object repository >select object and right click >choose rename option
>modify the name>release the mouse.>close repository
b) Shared Repository:
Resources >object repository manager>file>open>browse path of the repository file
>file>enable editing>select object &Right click>choose rename option>modify the name
> release mouse>save the file & close repository manager.

Deleting Objects
a) Local Repository:
Resources > object repository >select object and right click >choose delete option >confirm
deletion>. >close repository
b) Shared Repository:
Resources >object repository manager>file>open>browse path of the repository file >file>enable
editing>select object &Right click>choose delete option>confirm the deletion >save the file &
close repository manager.
Associating Object Repositories to an Action/Test
1) Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate
with an action>click ok
QUALITY THOUGHT QTP-MATERIAL

Page 23 of 93

2) Repositoriescollection.Add Repository file path (It is Used to Associate Repository to QTP at
Run Time)
Merging Repositories
Resources > object repository manager>tools>object repository merge tool >browse path of the first
repository> browse path of the second repository>click ok>click close>save the merged repository>close
the repository manager.

Note: After merging also, source repository files will be available, if we do not want source files we can
delete.

Defining New Test Objects

Navigation: Object>Define new test object >Select Environment>Select Class of the object>Enter name
of the object>Click Add>click close>Select object >select property name>enter value (like this select one
by one properties and enter values)>save

Note: This feature can be used for preparing tests before the AUT is ready.

Spying Objects

For getting objects information, (Test objects names, property & Values) QTP is providing a feature
called Object Spy, using this we can get objects information.

Navigation>Tools>object spy>take hand icon & Show the object>get information (Object Spy shows the
specific objects all available properties with their values)

Note: As Object spy is an important feature, it can be available in 3 Areas. (1. In tools Menu 2. In local
repository 3. In Repository manager)


View Options
Locate in Repository

This feature can be used for identifying objects from application to repository.

Navigation: View>Locate in repository >show the object>click Ok>it locates specified object in the
repository.

Highlight in Application

This feature can be used for identifying objects from repository to application.

Navigation: Select object in the repository >view>highlight in application>it highlights specified objects
in the application.

Exporting Repository to an XML file

We can export our repository file to an xml file.

Navigation: File >export Test objects to XML Enter the file name and Save with xml extension.

QUALITY THOUGHT QTP-MATERIAL

Page 24 of 93

Importing Repository from XML file.

We can import XML file to our repository.

Navigation: File>import from XML >browse path of the XML file >it loads objects.

Note: The purpose of this feature is Editing objects information outside of the QTP

Global or Shared Object Repository is preferable when application is dynamic and object
description change frequently
Between Shared and local object repository , shared object repository is more commonly used in
automation projects
But it has maintenance and administration overheads as compared to local object repository.

To create and use a shared object repository you need to perform three broad steps
1) Creating a Shared Object Repository
2) Associating a Shared Object Repository
3) Editing a Shared Object Repository

1) Creating a Shared Object Repository
All repositories are local by default. If you want to Create a Shared Object repository
Select Resources>Click on Object Repository Manager. Object Repository Manger will open
Repository files have an extension .tsr .Give a suitable name say "qtt and save
The Shared Repository File is now created

2) Associating a Shared Object Repository
Next step is to associate the repository to your test, which enables you to use it
To associate repository with a test, Click Resources > Associate Repository
You can select the Repository to associate with Actions available in your test.
Now you can now use this shared repository to develop your test
3) Editing a Shared Object Repository
You can use the Object Repository Manager to Edit a Shared Repository.
Select Resources > Object Repository Manager .Open the Object Repository we created "qtt"
By Default, Repository is opened in Read-only mode. To enable editing click File > Enable
Editing
Once editing is enabled you can all the operations like cut , copy , pate , rename objects etc that
you can also do in Object Repository
Using Object Repository Manager is you can compare two Object Repositories .QTP will give
you a static's of what's unique and common in both the repositories
You can use the Object repository merge to

Convert Local object Repository to Shared Object Repository
All repositories are local by default. To create a Shared Object Repository, in the Object
Repository Dialog Box , Click File > Export Local Objects
Repository files have an extension .tsr .Give a suitable name say "quality and save
The Shared Repository File is now created



QUALITY THOUGHT QTP-MATERIAL

Page 25 of 93

Configure Web Object Properties into Object Identification Tool
S.No Web UI Object Name Test Object Property
1 Browser Name
2 Page Title
3 Frame Name
4 WebTable Name
5 WebEdit Name
6 WebList Name, allitems
7 WebRadiGroup Name,allitems
8 WebCheckBox Name
9 Image File Name
10 WebButtomn Name, Type
11 File Name
12 Link Name,Innertext,href
13 WebElement Name, Innertext, href
14 Dialog Box Name, regexptitle

Relation Between Object Identification tool and Object Repository/Object Repository manager
OR/ORM and Object Identification tool go hand in hand and they are both sides of same coin.
Whatever configured in object identification tool reflects in ORM while adding Objects.

Suppose If you try to Add the Web UI WebButton Object to the Object Repository.
The changes in Mandatory properties in Object Identification tool will appear as Description
properties in the right pane of the Object Repository
As below figs shown




QUALITY THOUGHT QTP-MATERIAL

Page 26 of 93



QTP Actions:

Action: Set of Statements for perfoming a Task(s)
We divide our test into actions to streamline the process of testing.

Purpose of Actions:

For understandability

For reusing components

Types of Actions:

1) Non Re usable actions
2) Re usable actions
3) External actions

Operations on Actions:

Creating Actions

Splitting Actions

Renaming Actions

Deleting Actions

Calling an Action

Copying an Action

Making an Action Reusable/Non Reusable

Creating an Action:
Insert>call to new action>enter name of the action>click ok
Steps:
QUALITY THOUGHT QTP-MATERIAL

Page 27 of 93


1. Create required actions(ex login, insert,delte)
2. Prepare Scripts for those actions.

Splitting an action:

Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name &
action 2 name.

Steps:
1. Generate total test in the default action
2. Split into meaningful actions.

Note: At a time we can split one actions into 2 actions.
Renaming actions:
Select desired action in action drop down box> edit menu>action>rename action>modify the name>click
ok.
Deleting Actions:
Select desired action in action drop down box>edit menu>action>delete action>confirm deletion.
Calling an action:
Insert>call to existing action>browse path of the test>select desired action>click ok.

Note: U cant edit

Copying an action:
Insert>call to copy of action>browse path of the test>select desired action>click ok.

Note: we can edit this action.

Making an action reusable:
Select Non Reusable action >edit >action>action properties>check reusable action check box >click ok.
VBSCRIPT VARIABLES AND DATATYPES
What Is a Variable?
A variable is a convenient placeholder that refers to a computer memory location where you can store
program information that may change during execution
(Or)
Variable is a named memory location for storing program information
Declaring Variables
We declare variables explicitly in our script using the Dim statement, the Public statement, and the
Private statement. We declare multiple variables by separating each variable name with a comma.
For example: Dim Top, Bottom, Left, Right
QUALITY THOUGHT QTP-MATERIAL

Page 28 of 93

We can also declare a variable implicitly by simply using its name in our script. Generally it is not a good
practice because you could misspell the variable name in one or more places, causing unexpected results
During execution. For that reason, the Option Explicit statement is available to require explicit declaration
of all variables. The Option Explicit statement should be the first statement in the script.
Purpose of Variable:
a) Comparing values
Example:
Dim x,y,a
x=100
y=100
a=x=y
Msgbox a 'It returns True
b) Holding Program Result
Example:
Cost=Tickets*Price

c) Passing parameters
d) To store data that returned by functions
Example:
myDate=Now It returns current data & time
e) To hold data
Example:
myName=Quality thought

Option explicit:
When you use the Option Explicit statement, you must explicitly declare all variables using the Dim,
Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs.
Naming Restrictions
Variable names follow the standard rules for naming anything in VBScript. A variable name:
Must begin with an alphabetic character.
Cannot contain an embedded period.
Must not exceed 255 characters.
Must be unique in the scope in which it is declared.
Assigning Values to Variables
Values are assigned to variables creating an expression as follows: the variable is on the left side of the
expression and the value you want to assign to the variable is on the right.
For example: B = 200
DATATYPES
What Are VBScript Data Types?
QUALITY THOUGHT QTP-MATERIAL

Page 29 of 93

VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain
different kinds of information, depending on how it's used. Because Variant is the only data type in
VBScript, it's also the data type returned by all functions in VBScript.
At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number
when you use it in a numeric context and as a string when you use it in a string context. That is, if you're
working with data that looks like numbers, VBScript assumes that it is numbers and does the thing that is
most appropriate for numbers. Similarly, if you're working with data that can only be string data,
VBScript treats it as string data. Of course, you can always make numbers behave as strings by enclosing
them in quotation marks (" ").
Variant Subtypes
The following table shows the subtypes of data that a Variant can contain.
Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length
string ("") for string variables.
Null Variant intentionally contains no valid data.
Boolean Contains either True or False.
Byte Contains integer in the range 0 to 255.
Integer Contains integer in the range -32,768 to 32,767.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single Contains a single-precision, floating-point number in the range -3.402823E38
to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for
positive values.
Double Contains a double-precision, floating-point number in the range -
1.79769313486232E308 to -4.94065645841247E-324 for negative values;
4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date
(Time)
Contains a number that represents a date between January 1, 100 to
December 31, 9999.
String Contains a variable-length string that can be up to approximately 2 billion
characters in length.
Object Contains an object.
Error Contains an error number.
Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a predetermined
order called operator precedence. You can use parentheses to override the order of precedence and force
some parts of an expression to be evaluated before others. Operations within parentheses are always
performed before those outside. Within parentheses, however, standard operator precedence is
maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated first,
comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators
QUALITY THOUGHT QTP-MATERIAL

Page 30 of 93

all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.
Arithmetic and logical operators are evaluated in the following order of precedence.
Arithmetic
Description Symbol
Exponentiation ^
Unary negation -
Multiplication *
Division /
Integer division \
Modulus arithmetic Mod
Addition +
Subtraction -
String concatenation &

Comparison
Description Symbol
Equality =
Inequality <>
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Object equivalence Is

Logical
Description Symbol

Logical negation
Not
Logical conjunction And
Logical disjunction Or
Logical exclusion Xor
Logical equivalence Eqv
Logical implication Imp

When multiplication and division occur together in an expression, each operation is evaluated as it occurs
from left to right. Likewise, when addition and subtraction occur together in an expression, each operation
is evaluated in order of appearance from left to right.
The string concatenation (&) operator is not an arithmetic operator, but in precedence it falls after all
arithmetic operators and before all comparison operators. The Is operator is an object reference
QUALITY THOUGHT QTP-MATERIAL

Page 31 of 93

comparison operator. It does not compare objects or their values; it checks only to determine if two object
references refer to the same object.
The logic of OR is that if at least one of the inputs are True, the output is true;
True OR True = True
True OR False = True
False OR True = True
False OR False = False
XOR only returns True if one and only one of the inputs is True.
True Xor True = False
True Xor False = True
False Xor True = True
False Xor False = False
Imp returns false if first one is true and second one false except this it returns true.
True imp True = True
True imp False = False
False imp True = True
False imp False = True
CONDITIONAL AND LOOPING STATEMENTS
We can control the flow of our script with conditional statements and looping statements.

Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The
following conditional statements are available in VBScript:
Conditional Statements:
1) IfThenElse Statement
If...Then...Else: Conditionally executes a group of statements, depending on the value of an
expression.
Syntax:

If condition Then statements [Else elsestatements ]

OR

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If
QUALITY THOUGHT QTP-MATERIAL

Page 32 of 93


2) Select Case Statement
Select Case: Executes one of several groups of statements, depending on the value of an expression.
Syntax:
Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else expressionlist-n
[elsestatements-n]]
End Select

Example:
'Select Case
Colour =Ucase( Inputbox("Please enter the colour of your choice"))

Select Case Colour

Case "RED"
MsgBox "Colour selected is Red"
Case "BLUE"
MsgBox "Colour selected is Red"
Case "GREEN"
MsgBox "Colour selected is Red"
Case ELSE
MsgBox "Invalid Colour"
End Select

Looping statements are used to run the same block of code a specified number of times.
In VBScript we have four looping statements:
1) Using Do Loops
We can use Do...Loop statements to run a block of statements an indefinite number of times.

The statements are repeated either while a condition is True or until a condition becomes True.
a) Repeating Statements While a Condition is True
Repeats a block of statements while a condition is True or until a condition becomes True

i) Do While condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:

Example:

QUALITY THOUGHT QTP-MATERIAL

Page 33 of 93

Dim x
Do While x<5 x=x+1
Msgbox "Hello Quality Thought"
Msgbox "Hello QTP"
Loop

ii) Do
Statements
-----------
-----------
Loop While condition

Example:

Dim x
x=1
Do
Msgbox "Hello Quality Thought"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
b) Repeating a Statement Until a Condition Becomes True
iii) Do Until condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:
Example:

Dim x
Do Until x=5 x=x+1
Msgbox "Quality Thought"
Msgbox "Hello QTP"
Loop

Or, we can use this below syntax:

iv) Do
Statements
-----------
-----------
Loop Until condition
Or, we can use this below syntax:

Example:

Dim x
x=1
QUALITY THOUGHT QTP-MATERIAL

Page 34 of 93

Do
Msgbox Hello Quality Thought
Msgbox "Hello QTP"
x=x+1
Loop Until x=5
2 While...Wend Statement
Executes a series of statements as long as a given condition is True.

Syntax:
While condition
Statements
-----------
-----------
Wend

Example:

Dim x
x=0
While x<5 x=x+1
msgbox "Hello Quality Thought"
msgbox "Hello QTP"
Wend
3) For...Next Statement
Repeats a group of statements a specified number of times.
Syntax:
For counter = start to end [Step step]
statements
Next

Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello Quality Thought"
Next
4) For Each...Next Statement
Repeats a group of statements for each element in an array or collection.

Syntax:

QUALITY THOUGHT QTP-MATERIAL

Page 35 of 93

For Each item In array
Statements
Next

Example:
3) Dim a,b,x (3)
a=20
b=30
x(0)= "Addition is "& a+b
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b

For Each element In x
msgbox element
Next
4) MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
VbScript Functions:
String Functions

Function Description
InStr Returns the position of the first occurrence of one string within another. The
search begins at the first character of the string
InStrRev Returns the position of the first occurrence of one string within another. The
search begins at the last character of the string
LCase Converts a specified string to lowercase
Left Returns a specified number of characters from the left side of a string
Len Returns the number of characters in a string
LTrim Removes spaces on the left side of a string
RTrim Removes spaces on the right side of a string
Trim Removes spaces on both the left and the right side of a string
Mid Returns a specified number of characters from a string
Replace Replaces a specified part of a string with another string a specified number of
times
Right Returns a specified number of characters from the right side of a string
Space Returns a string that consists of a specified number of spaces
StrComp Compares two strings and returns a value that represents the result of the
comparison
String Returns a string that contains a repeating character of a specified length
StrReverse Returns a string in which the character order of a specified string is reversed.
UCase Converts a specified string to uppercase
QUALITY THOUGHT QTP-MATERIAL

Page 36 of 93

Array Functions

Function Description
Array Returns a variant containing an array
Filter Returns a zero-based array that contains a subset of a string array based on a
filter criteria
IsArray Returns a Boolean value that indicates whether a specified variable is an
array
Join Returns a string that consists of a number of substrings in an array
LBound Returns the smallest subscript for the indicated dimension of an array
Split Returns a zero-based, one-dimensional array that contains a specified number
of substrings
UBound Returns the largest subscript for the indicated dimension of an array
Date/Time Functions
Function Description
CDate Converts a valid date and time expression to the variant of subtype Date
Date Returns the current system date
DateAdd Returns a date to which a specified time interval has been added
DateDiff Returns the number of intervals between two dates
DatePart Returns the specified part of a given date
DateSerial Returns the date for a specified year, month, and day
DateValue Returns a date
Day Returns a number that represents the day of the month (between 1 and 31,
inclusive)
FormatDateTime Returns an expression formatted as a date or time
Hour Returns a number that represents the hour of the day (between 0 and 23,
inclusive)
IsDate Returns a Boolean value that indicates if the evaluated expression can be
converted to a date
Minute Returns a number that represents the minute of the hour (between 0 and 59,
inclusive)
Month Returns a number that represents the month of the year (between 1 and 12,
inclusive)
MonthName Returns the name of a specified month
Now Returns the current system date and time
Second Returns a number that represents the second of the minute (between 0 and 59,
inclusive)
Time Returns the current system time
Timer Returns the number of seconds since 12:00 AM
TimeSerial Returns the time for a specific hour, minute, and second
TimeValue Returns a time
Weekday Returns a number that represents the day of the week (between 1 and 7,
inclusive)
WeekdayName Returns the weekday name of a specified day of the week
Year Returns a number that represents the year
Math Functions

QUALITY THOUGHT QTP-MATERIAL

Page 37 of 93

Function Description
Abs Returns the absolute value of a specified number
Atn Returns the arctangent of a specified number
Cos Returns the cosine of a specified number (angle)
Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number
Int Returns the integer part of a specified number
Fix Returns the integer part of a specified number
Log Returns the natural logarithm of a specified number
Oct Returns the octal value of a specified number
Rnd Returns a random number less than 1 but greater or equal to 0
Sgn Returns an integer that indicates the sign of a specified number
Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified number
Tan Returns the tangent of a specified number (angle)
Other Functions

Function Description
CreateObject Creates an object of a specified type
Eval Evaluates an expression and returns the result
GetLocale Returns the current locale ID
GetObject Returns a reference to an automation object from a file
GetRef Allows you to connect a VBScript procedure to a DHTML event on your
pages


String Functions

Instr: Returns the position of the first occurrence of one string within another. The search begins at the
first character of the string
Syntax:
InStr([start, ]string1, string2[, compare])
Arguments
Start Optional. Numeric expression that sets the starting position for each search. If omitted search
begins at the first character position. If start contains Null
an error occurs. The start argument is required if compare is specified.
String1 Required. String expression being searched.
String2 Required. String expression searched for.
Compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings.
See Settings section for values. If omitted, a binary comparison is performed.
Settings
The compare argument can have the following values:
Constant Value Description
QUALITY THOUGHT QTP-MATERIAL

Page 38 of 93


Example:
1) Dim Strname
Strname = Quality Thought
Msgbox Instr (Strname,T)
Return value = 9
Note: By default it takes the Binary comparison 0
2) Dim Strname , SearchChar
Strname = Quality Thought
SearchChar = T
Msgbox Instr (10, Strname, SearchChar) A binary comparison starting at position 10
Return value = 0
3) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = t
Msgbox Instr (7, Strname, SearchChar, 1) A Textual comparison starting at position 7
Return value = 9
4) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = t
Msgbox Instr (1, Strname, SearchChar, 0) A binary comparison starting at position 1
Return value = 6
InStrRev: Returns the position of the first occurrence of one string within another. The search begins at
the last character of the string
Syntax:
InStrRev (string1, string2 [, start [, compare]])
Examples:
5) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = t
Msgbox InStrRev (Strname, SearchChar) Comparison is binary by default
Return value = 15
6) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = t
Msgbox InStrRev (Strname, SearchChar, 14,0) A binary comparison staring at position
14
Return value = 6
7) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = t
Msgbox InStrRev (Strname, SearchChar,14,1) A textual Comparison starting at position
14
Return value = 9
8) Dim Strname, SearchChar
Strname = Quality Thought
SearchChar = T
Msgbox InStrRev (Strname, SearchChar,8) A binary comparison starting at position 8
vbBinaryCompare 0 Perform a binary comparison.
vbTextCompare 1 Perform a textual comparison.
QUALITY THOUGHT QTP-MATERIAL

Page 39 of 93

Return value = 0

Lcase: Converts a specified string to lowercase
Syntax:
Lcase (string)
Arguments
String The string is any valid string expression. If string contains Null, Null is returned.

Example:
Dim Strname
Strname = QTP Class
Msgbox Lcase (Strname)
Return value = qtp class

Ucase: Converts a specified string to uppercase
Syntax:
Ucase (string)
Arduments
String The string is any valid string expression. If string contains Null, Null is returned.

Example:
Dim Strname
Strname = quality Thought
Msgbox Ucase (Strname)
Return value = QUALITY THOUGHT

Left: Returns a specified number of characters from the left side of a string
Syntax:
Left(string, length)
Arguments
string String expression from which the leftmost characters are returned. If string contains Null,
Null is returned.
length Numeric expression indicating how many characters to return. If 0, a zero-length string("") is
returned. If greater than or equal to the number of characters in string, the entire string is
returned.

Example:
Dim Strname
Strname = QTP Vb Script
Msgbox Left(Strname,3)
Return value = QTP
Right: Returns a specified number of characters from the right side of a string
Syntax:
Right(string, length)
Arguments
string String expression from which the leftmost characters are returned. If string contains Null,
Null is returned.
length Numeric expression indicating how many characters to return. If 0, a zero-length string("") is
returned. If greater than or equal to the number of characters in string, the entire string is
QUALITY THOUGHT QTP-MATERIAL

Page 40 of 93

returned.

Example:
Dim strname
Strname = QTP VB Script
Msgbox Right (Strname,6)
Return value = Script
Len: Returns the number of characters in a string
Syntax:
Len (string | varname)
Arguments
string Any valid string expression. If string contains Null, Null is returned
varname Any valid variable name. If varname contains Null, Null is returned

Example:
Dim Strname
Strname = Quality thought
Msgbox Len (Strname)
Return value = 15
LTrim: Removes spaces on the left side of a string
Syntax:
LTrim (String)
Arguments
String The string is any valid string expression. If string contains Null, Null is returned.

Example:
Dim Strname
Strname = Quality
Msgbox LTrim (Strname)
Return value = Quality
RTrim: Removes spaces on the right side of a string
Syntax:
RTrim (String)
Arguments
String The string is any valid string expression. If string contains Null, Null is returned.
Example:
Dim Strname
Strname = Quality
Msgbox RTrim (Strname)
Return value = Quality
Trim: Removes spaces on both the left and the right side of a string
Syntax:
Trim(String)
Arguments
String The string is any valid string expression. If string contains Null, Null is returned.

QUALITY THOUGHT QTP-MATERIAL

Page 41 of 93

Example:
Dim Strname
Strname = Quality thought
Msgbox Trim (Strname)
Return value = Quality thought
Mid: Returns a specified number of characters from a string
Syntax:
Mid(string, start[, length])
Arguments
string String expression from which characters are returned. If string contains Null, Null is returned.
start Character position in string at which the part to be taken begins. If start is greater than the
number of characters in string, Mid returns a zero-length string ("").
length Number of characters to return. If omitted or if there are fewer than length characters in the text
(including the character at start), all characters from the start position to the end of the string
are returned.

Example:
1) Dim Strname
Strname = Quality thought QTP Class
In the Above String I want to retrieve only QTP
Msgbox Mid(Strname,17,3)
Return value = QTP
2) Dim Strname
Strname = Automation Class
In the Above String I want to retrieve only mation
Msgbox Mid(Strname,5,6)
Return value = mation
Replace: Returns a string in which a specified substring has been replaced with another substring a
specified number of times.
Syntax:
Replace (expression, find, replacewith [, start [, count [, compare]]])
Arguments
expression Required. String expression containing substring to replace.
find Required. Substring being searched for
replacewith Required. Replacement substring.
start Optional. Position within expression where substring search is to begin. If omitted, 1 is
assumed. Must be used in conjunction with count
count Optional. Number of substring substitutions to perform. If omitted, the default value is -
1, which means make all possible substitutions. Must be used in conjunction with start.
compare Optional. Numeric value indicating the kind of comparison to use when evaluating
substrings. See Settings section for values. If omitted, the default value is 0, which means
perform a binary comparison.

Example:
1) Dim Strname
QUALITY THOUGHT QTP-MATERIAL

Page 42 of 93

Strname = Automation Mercury Tool
Msgbox Replace (Strname, Mercury , HP)
Return value = Automation HP Tool
Note: Default comparison is Binary Comparison
2) Dim Strname
Strname = Automation Mercury Tool
Msgbox Replace (Strname, mercury , HP)
Return value = Automation Mercury Tool
Note: Default comparison is Binary Comparison
3) Dim Strname
Strname = Automation Mercury Tool
Msgbox Replace (Strname, mercury , HP,1,1,1)
Return value = Automation HP Tool
Note: A textual comparison starting at position 1.
4) Dim Strname
Strname = Automation Mercury Tool
Msgbox Replace (Strname, Mercury , HP,5,3)
Return value = mation HP Tool
Note: A Binary Comparison starting at position 5
Space: Returns a string that consists of a specified number of spaces
Syntax:
Space (number)
Argument
number The number argument is the number of spaces you want in the string

Example:
Msgbox Quality&space (4) & Thought
Return value = Quality Thought
Note: Here the above Example Returns the String with 4 spaces

StrComp: Compares two strings and returns a value that represents the result of the comparison
Syntax:
StrComp (string1, string2 [, compare])
Arguments
string1 Required. Any valid string expression.
string2 Required. Any valid string expression.
Compare Optional. Numeric value indicating the kind of comparison to use when evaluating strings. If
omitted, a binary comparison is performed. See Settings section for values.
Settings
The compare argument can have the following values:

Constant Value Description
vbBinaryCompare 0 Perform a binary comparison.
vbTextCompare 1 Perform a textual comparison.

QUALITY THOUGHT QTP-MATERIAL

Page 43 of 93

Return Values
The StrComp function has the following return values:
If StrComp returns
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1
string1 or string2 is Null Null


Example:
1) Dim Str1,Str2
Str1 = "Automation"
Str2 = "automation"
Msgbox Strcomp (Str1, Str2)
Return value = -1
Note: Comparison is Binary by Default
2) Dim Str1,Str2
Str1 = "Automation"
Str2 = "automation"
Msgbox Strcomp (Str1, Str2,1)
Return value = 0

3) Dim Str1,Str2
Str1 = "automation"
Str2 = "Automation"
Msgbox Strcomp (Str1, Str2,0)
Return value = 1
String: Returns a string that contains a repeating character of a specified length
Syntax:
String(number, character)
Arguments:
number Length of the returned string. If number contains Null, Null is returned.
character Character code specifying the character or string expression whose first character
is used to build the return string. If character contains Null, Null is returned

Example:
Msgbox String (5, Automation)
Return value = AAAAA

StrReverse: Returns a string in which the character order of a specified string is reversed.
Syntax:
StrReverse (string1)
Argument:
String1 The string1 argument is the string whose characters are to be reversed. If string1 is a zero-
length string (""), a zero-length string is returned. If string1 is Null, an error occurs.
Example:
Dim String1
QUALITY THOUGHT QTP-MATERIAL

Page 44 of 93

String1 = Automation
Msgbox StrReverse (String1)
Return value = noitamotuA
Array Functions

Array: Returns a variant containing an array
Syntax:
Array (arglist)
Arglist The required arglist argument is a comma-delimited list of values that are assigned to the
elements of an array contained with the Variant. If no arguments are specified, an array of zero
length is created.

Example:
1) Dim A
A = Array (10, 20, 30)
B = A (2) ' B is now 30
Redim A (4)
A (4) = QTP Class
Msgbox A (4)
Return value = QTP Class
2) 'Single dimensional Array with five elements
Dim Num(3)
Num(0)=10
Num(1)=20
Num(2)=30
Msgbox Num (0) 'Output 10
Msgbox Num (1) 'Output 20
Msgbox Num (2) 'Output 30
3) 'multidimensional array
Dim DNum (3, 2)
DNum (0, 0) =10
DNum (0, 1) =20
DNum (1, 0) =30
DNum (1, 1) =40
DNum (2, 0) =50
DNum (2, 1) =60
Msgbox DNum (0, 0) 'Output 10
Msgbox DNum (0, 1) 'Output 20
Msgbox DNum (1, 0) 'Output 30
Msgbox DNum (1, 1) 'Output 40
Msgbox DNum (2, 0) 'Output 50
Msgbox DNum (2, 1) 'Output -->60

Filter: Returns a zero-based array containing a subset of a string array based on a specified filter criteria.
Syntax:
Filter (InputStrings, Value [, Include [, Compare]])
QUALITY THOUGHT QTP-MATERIAL

Page 45 of 93

Arguments
InputStrings Required. One-dimensional array of strings to be searched.
Value Required. String to search for.
Include Optional. Boolean value indicating whether to return substrings that include or exclude
Value. If Include is True, Filter returns the subset of the array that contains Value as a
substring. If Include is False, Filter returns the subset of the array that does not contain
Value as a substring.
Compare Optional. Numeric value indicating the kind of string comparison to use. See Settings
section for values.
Example:
Dim MyArray (3)
MyArray (0) = "Sunday"
MyArray (1) = "Monday"
MyArray (2) = "Tuesday"
MyIndex = Filter (MyArray, "Mon")
Msgbox MyIndex (0)
Return value = "Monday"
IsArray Function: IsArray: Returns a Boolean value indicating whether a variable is an array.
Syntax:
IsArray (varname)
Varname The varname argument can be any variable.
Example:
Dim MyArray (3)
MyArray (0) = "Sunday"
MyArray (1) = "Monday"
MyArray (2) = "Tuesday"
MyVariable = IsArray(MyArray)
Return value = True
Split Function:
Returns a zero-based, one-dimensional array containing a specified number of substrings.
Syntax:
Split (expression[, delimiter[, count[, compare]]])
Arguments
expression Required. String expression containing substrings and delimiters. If expression is a
zero-length string, Split returns an empty array, that is, an array with no elements and
no data.
delimiter Optional. String character used to identify substring limits. If omitted, the space
character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a
single-element array containing the entire expression string is returned.
QUALITY THOUGHT QTP-MATERIAL

Page 46 of 93

count Optional. Number of substrings to be returned; -1 indicates that all substrings are
returned.
compare Optional. Numeric value indicating the kind of comparison to use when evaluating
substrings. See Settings section for values.
Example:
1) Dim Strname,Str
Strname = QualityXthxoughtxtechxnoXlogixes
Str = Split(Strname,x)
Msgbox Str(0) Output QualityXth
Msgbox Str(1) Output ought
--------
Msgbox Str(4) Output es
Note: The above example the Comparison is Binary by default
2) Dim Strname,Str
Strname = QualityXthxoughtxtechxnoXlogixes
Str = Split(Strname,x,-1,1)
Msgbox Str(0) Output Quality
Msgbox Str(1) Output th
--------
--------
Msgbox Str(6) Outputes

Join: Returns a string that consists of a number of substrings in an array
Syntax:
Join (list [, delimiter])
Arguments:

list Required. One-dimensional array containing substrings to be joined.
delimiter Optional. String character used to separate the substrings in the returned string. If omitted,
the space character (" ") is used. If delimiter is a zero-length string, all items in the list are
concatenated with no delimiters.

Example:
Dim MyArray (3)
MyArray (0) = "Welcome "
MyArray (1) = "to "
MyArray (2) = "QTP "
MyArray (3) = "Class"
MyString = Join (MyArray)
Msgbox MyString

LBound: Returns the smallest subscript for the indicated dimension of an array
Syntax:
LBound (arrayname [, dimension])
Arguments:
arrayname: Name of the array variable; follows standard variable
naming conventions.
dimension: Whole number indicating which dimension's lower
bound is returned. Use 1 for the first dimension, 2 for
the second, and so on. If dimension is omitted, 1 is
QUALITY THOUGHT QTP-MATERIAL

Page 47 of 93

assumed.
Example:
1) Dim LArr
LArr = Array (10, 20, 30)
Msgbox Lbound (LArr, 1) 'Output 0
2) ''multidimensional array
Dim Lmarr(3,2)
Msgbox LBound (Lmarr, 2) 'Output 0
UBound: Returns the largest subscript for the indicated dimension of an array
Syntax:
UBound (arrayname [, dimension])
Arguments:

arrayname: (Required) Name of the array variable; follows standard variable naming conventions.
dimension:
(Optional) Whole number indicating which dimension's upper bound is returned. Use 1
for the first dimension,
2 for the second, and so on. If dimension is omitted, 1 is assumed.
Example:
1) Dim UArr
UArr = Array (10, 20, 30)
Msgbox Ubound (UArr, 1) 'Output 2
2) ''multidimensional array
Dim Umarr (3, 2, 4)
Msgbox UBound (Umarr, 1) 'Output 3
Msgbox UBound (Umarr, 2) 'Output 2
Msgbox UBound (Umarr, 3) 'Output 4
Date/Time Functions
Date: Returns the current system date
Syntax: Date

Example:
Msgbox Date
It displays the current system date
IsDate: Returns a Boolean value that indicates if the evaluated expression can be converted to a date
Syntax:
QUALITY THOUGHT QTP-MATERIAL

Page 48 of 93

IsDate(expression)
Exapression The expression argument can be any date expression or string expression recognizable as
a date or time
Example:
Dim MyDate, YourDate, NoDate, MyCheck
MyDate = "October 19, 1962"
YourDate = #10/19/62#
NoDate = "Hello"
MyCheck = IsDate (MyDate)
Returns True.
MyCheck = IsDate (YourDate)
Returns True.
MyCheck = IsDate (NoDate)
Returns False.
Time: Returns a Variant of subtype Date indicating the current system time.
Syntax: Time
Example:
Msgbox Time
It displays the current system time.
DateAdd: Returns a date to which a specified time interval has been added.
Syntax: DateAdd (interval, number, date)
Arguments:
Settings
The interval argument can have the following values:
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second


Interval (Required) String expression that is the interval you want to add. See Settings
section for values.
Number (Required) Numeric expression that is the number of interval you want to add.
The numeric expression can either be positive, for dates in the future, or
negative, for dates in the past.

Date (Required) Variant or literal representing the date to which interval is added.
QUALITY THOUGHT QTP-MATERIAL

Page 49 of 93

Example:
NewDate = DateAdd("m", 1, "31-Dec-12")
msgbox NewDate
Return Value = 1/31/2013

DateDiff: Returns the number of intervals between two dates
Syntax: DateDiff (interval, date1, date2 [, firstdayofweek [, firstweekofyear]])
Arguments:

Interval (Required) String expression that is the interval you want to use to
calculate the differences between
date1 and date2.
date1, date2 (Required) Date expressions. Two dates you want to use in the
calculation.
Firstdayofweek (Optional) Constant that specifies the day of the week. If not specified,
Sunday is assumed.
Firstweekofyear (Optional) Constant that specifies the first week of the year. If not
specified, the first week is assumed to be the week in which January
1 occurs.

Example:
Diffdate = Datediff ("y","15-aug-10","15-aug-12")
Msgbox Diffdate
Return Value = 731

DatePart: Returns the specified part of a given date.

Syntax: DatePart (interval, date [, firstdayofweek [, firstweekofyear]])

Arguments:
Interval (Required) String expression that is the interval of time you
want to return.
Date (Required) Date expression you want to evaluate.
firstdayof week (Optional) Constant that specifies the day of the week. If not
specified, Sunday is assumed.
Firstweekofyear (Optional) Constant that specifies the first week of the year. If
not specified, the first week is assumed to be the week in which
January 1 occurs.

Example:
GetQuarter = DatePart ("q", Date)
Msgbox GetQuarter

Day: Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Syntax: Day (date)

Date expression represent a date. If date contains Null,
Null is returned.
QUALITY THOUGHT QTP-MATERIAL

Page 50 of 93


Example:
MyDay = Day("Aug 15, 2010")
Msgbox MyDay
Return value = 15
MyDay2 =Day ("15/8/2010")
Msgbox MyDay2
Return value = 15

Month: Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Syntax: Month (date)

Date Expressions represent a date. If date contains Null, Null is returned.

Example:
Msgbox Month ("8-15-2010")
Return value = 8
Msgbox Month ("15/8/2010")
Return value = 8
Msgbox Month ("August 15, 2010")
Return value = 8
MonthName: Returns a string indicating the specified month.

Syntax: MonthName (month [, abbreviate])

Arguments:

Month (Required) The numeric designation of the month. For example, January is
1, February is 2, and so on.
Abbreviate (Optional) Boolean value that indicates if the month name is to be
abbreviated. If omitted, the default is False, which means that the month
name is not abbreviated.


Example:
Msgbox MonthName (11, true)
Return value = Nov
Msgbox MonthName (8, false)
Return value = August
Msgbox MonthName (9)
Return value = September

Weekday: Returns a whole number representing the day of the week.

Syntax: Weekday (date, [firstdayofweek])

Arguments:

QUALITY THOUGHT QTP-MATERIAL

Page 51 of 93

Date Any expression that can represent a date. If date contains
Null, Null is returned.
Firstdayofweek A constant that specifies the first day of the week. If
omitted, vbSunday is assumed.
Example: s
Msgbox Weekday("August 15, 2013")
Return value = 5
WeekdayName: Returns a string indicating the specified day of the week.

Syntax: WeekdayName (weekday, abbreviate, firstdayofweek)

Arguments:

weekday: (Required) The numeric designation for the day of the week. Numeric
value of each day depends on setting of the firstdayofweek setting.
abbreviate: (Optional) Boolean value that indicates if the weekday name is to be
abbreviated. If omitted, the default is False, which means that the
weekday name is not abbreviated.
firstdayofweek: (Optional) Numeric value indicating the first day of the week.

Example:
Msgbox WeekdayName (5)
Return value = Thursday

Year: Returns a whole number representing the year.

Syntax: Year (date)

Arguments:
date: Any expression that can represent a date. If date contains
Null, Null is returned.

Example:
Msgbox Year("15-08-2010")
Rtuen value = 2010
Msgbox Year("15/8/2010")
Return value =2010
Msgbox Year("November 01, 2010")
Return value = 2010

Hour: Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Syntax: Hour (time)

Arguments:
QUALITY THOUGHT QTP-MATERIAL

Page 52 of 93


Time is any expression that can represent a time. If time contains Null, Null is
returned.

Example:
Msgbox Hour(Now)
Displays the current system hour
Minute: Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.

Syntax: Minute (time)

Arguments:

time: is any expression that can represent a time. If time contains
Null, Null is returned.


Example:
Msgbox Minute(Now)
Displays the current system minute.

Second: Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax: Second (time)

Arguments:

Time is any expression that can represent a time. If time contains
Null, Null is returned.

Example:
Msgbox Second (Now)
Displays the current system second.

Now: Returns the current date and time according to the setting of your computer's system date and time.

Syntax: Now

Example:
Msgbox Now
Displays the current system date & time.

TimeSerial: Returns a Variant of subtype Date containing the time for a specific hour, minute, and
second.

Syntax: TimeSerial (hour, minute, second)

Arguments:

Hour Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or
QUALITY THOUGHT QTP-MATERIAL

Page 53 of 93

a numeric expression.
Minute Any numeric expression.
Second Any numeric expression.

Example:
Msgbox Timeserial (12,12,12)
Return value =12:12:12 PM

TimeValue: Returns a Variant of subtype Date containing the time.

Syntax: TimeValue(time)

Arguments:
Example:
Msgbox TimeValue("12:30:00")
Return value =12:30:00 PM

Other Functions

CreateObject:
Creates an object of a specified type
OR
Creates and returns a reference to an Automation object
Syntax:
CreateObject (servername.typename [, location])
Arguments:
servername Required. The name of the application providing the object.
typename Required. The type or class of the object to create.
location Optional. The name of the network server where the object is to be created.
Example:
1) To create the Excel Application
Set xlobj = CreateObject (Excel.Application)
2) To Create the Data base Connection Object
Set DbConn = CreateObject(Adodb.Connection)
3) To Create to Hold the Records in database Tables
Set Rs = CreateObject(Adodb.Recordset)
4) To Create the File System Object
Set fso = CreateObject (Scripting.FileSystemObject)
5) To Create Automation Object Model
Set aom = CrateObject (QuickTest.Application)
Eval:
Evaluates an expression and returns the result
Syntax:
Time is usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to
23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that
represents a time in that range. If time contains Null, Null is returned.
QUALITY THOUGHT QTP-MATERIAL

Page 54 of 93

result = ]Eval(expression)
Arguments:

result Optional. Variable to which return value assignment is made. If result is not specified,
consider using the Execute statement instead.
Expression Required. String containing any legal VBScript expression

Example:
Dim Var
Var = InputBox (Enter the var Type)
Select Case Eval(TypeName(Var))
Case "Integer" : MsgBox "Integer"
Case "Dictionary" : MsgBox "Dictionary"
Case "Nothing" : MsgBox "Nothing"
Case "String" : MsgBox "String"
End Select
User-defined functions
Functions and Library:
If you have repeatable steps in a test or an action then consider using a user-defined function. User-
defined functions will make your tests look shorter, easier to maintain, read and design. A user-defined
function can then be called from within an action.
Function:
Set of statements grouped together with input parameters and output is predefined. The entity is given
name and is invoked by the name. Once the function is defined, Next time onwards, if we need to invoke
these set of statements just invoke the name given to it.
Function Syntax:
Function <function name>(parameterlist)
<function name> = returnvalue
End Function
Library:
If the function is written inside automation script that function is available only to the script in which it
resides. To make the function available to other automation scripts as well we should transfer the function
into library file
A Library can be prepared by adding one or more functions to it
Question: When can the function be located? Inside library? Inside automation script?
Ans: you can write the function either in the automation script (or) In the function library is available only
to the automation script in which it is located.
QUALITY THOUGHT QTP-MATERIAL

Page 55 of 93

If the function should be shared across multiple automation scripts, then we write the function in the
library file
Advantages of writing/transferring function to Library
All functions of the project will be existing at one place hence easily manageable
Function of library are available to all automation scripts
The library file can be sent across to any one by email
The library file can be read by simple notepad application
Note: QTP file contains too many folders and supporting files in it. Hence each QTP automation
script is bulky(not flat file) file and it depends on size limitation of Email server to send the
automation script file
Create a Library file:
Go to File> New > function library
First you write a function in the automation script and check it is working fine. Once you are confident on
the function copy the function into a text file and save the text file with the library
How to access the function of Library file?
To access the function of a library follow the steps here under
Associate the library file to QTP
Open the Script and invoke the function with function name
Steps to Associate library to QTP:
1) Go to file > Settings

QUALITY THOUGHT QTP-MATERIAL

Page 56 of 93

2) Go to Settings > Resources > Associated function libraries

3) Click on Add and select the your library file
4) Click on Set as Default. Set as Default Button will make the library available to all
automation scripts that are being developed using QTP in that machine.
Different ways to associate the Function library
Based on the type of framework you are using, you can use any of the following methods to associate
function libraries to your QTP Script -
1) By using File > Settings > Resources > Associate Function Library option in QTP.
2) By using Automation Object Model (AOM).
3) By using ExecuteFile method.
4) Using LoadFunctionLibrary method.
In the above methods we already explain 1
st
method so we can go to the remaining method
2) Using Automation Object Model(AOM)
QTP AOM is a mechanism using which you can control various QTP operations from outside QTP.
Using QTP Automation Object Model, you can write a code which would open a QTP test and associate a
function library to that test.
Example: Using the below code, you can open QTP, then open any test case and associate a required
function library to that test case. To do so, copy paste the below code in a notepad and save it with a .vbs
extension.
QUALITY THOUGHT QTP-MATERIAL

Page 57 of 93













'Open QTP
Set objQTP = CreateObject("QuickTest.Application")
objQTP.Launch
objQTP.Visible = True

'Open a test and associate a function library to the test
objQTP.Open "C:\Automation\SampleTest", False, False

Set objLib = objQTP.Test.Settings.Resources.Libraries

'If the library is not already associated with the test case, associate it..
If objLib.Find("C:\SampleFunctionLibrary.vbs") = -1 Then ' If library is not already added
objLib.Add "C:\SampleFunctionLibrary.vbs", 1 ' Associate the library to the test case
End

3) Using ExecuteFile Method
ExecuteFile statement executes all the VBScript statements in a specified file. After the file has been
executed, all the functions, subroutines and other elements from the file (function library) are available to
the action as global entities. Simply put, once the file is executed, its functions can be used by the action.
You can use the below mentioned logic to use ExecuteFile method to associate function libraries to your
script.
Example: ExecuteFile D:\mylibrary.qfl

4 ) Using LoadFunctionLibrary method
LoadFunctionLibrary, a new method introduced in QTP 11 allows you to load a function library when a
step runs. You can load multiple function libraries from a single line by using a comma delimiter.

Example:
1) To Associate a single Function library
LoadFunctionLibrary D:\mylibrary.vbs
2) To Associate multiple function libraries
LoadFunctionLibrary D:\myLibrary1.qfl,D:\Mylibrary2.txt,D:\Mylibrary3.vbs
Examples of Functions:
****************************************
1) Write a function that perform arithmetic operations-Addition, Subtraction. Multiplication and
division On two variables
Function mathoperation (Byref x, Byref y, Byref arithmeticOperation)
Dim z
If arithmeticOperation = Addition Then
z = x + y
mathoperation = z
End if
If arithmeticOperation = Subtraction Then
z = x - y
QUALITY THOUGHT QTP-MATERIAL

Page 58 of 93

mathoperation = z
End if
If arithmeticOperation = Division Then
z = x/y
mathoperation = z
End if
If arithmeticOperation = Multiplication Then
z = x * y
mathoperation = z
End if
End Function
returnvalue = mathoperation (20,10, Addition)
returnvalue = mathoperation (20,10, Multiplication)
**********************************************************************
2) Write a Function to Launch websites Based on the keywordsYahoo, Google, Gmail, Facebook,
Twitter
Function openwebsite (keyword) Here By default parameter value is ByRef
If keyword = Yahoo then
Systemutil.Run iexplore.exe,www.yahoo.com
Openwebsite = Yahoo application is launched
End if
If keyword = Google then
Systemutil.Run iexplore.exe,www.google.com
Openwebsite = Google application is launched
End if
If keyword = Gmail then
Systemutil.Run iexplore.exe,www.gmail.com
Openwebsite = Gmail application is launched
End if
If keyword = Facebook then
Systemutil.Run iexplore.exe,www.facebook.com
Openwebsite = Facebook application is launched
End if
If keyword = Twitter then
Systemutil.Run iexplore.exe,www.twitter.com
Openwebsite = Twitter application is launched
End if
End function
returnvalue = openwebsite(Yahoo)
returnvalue = openwebsite(Facebook)
************************************************************
Regular Expression
Regular Expression Introduction
You have created a document and saved it to your hard disk. After few days again you want to update that
document, but you forgot where you saved. Now you started searching for that document. Do you go to
every folder in hard disk to search for it? No. You will just use search window to search the document
by using name. Unfortunately you didnt find any document on that name. So what will you do?
QUALITY THOUGHT QTP-MATERIAL

Page 59 of 93

Here exactly the concept of Regular Expression will come in to the picture.
A Regular Expression is a string that provides a complex search phrase.
If you create a word document then you will search for *.doc. Here the * indicates any name which are
there in specified disk.
As per the definition, * is a regular expression which provides a phrase to match any name of the
document.
Phraseis an expression consisting of one or more words.
I have used above concept to tell you that Regular Expressions are not new to us (Testers). Some how
we used it in regular activities but we dont know that these are Regular Expressions.
What is Regular Expression?
It is a way of representing data using symbols. They are often used within matching, searching or
replacing algorithms.
Regular Expressions in QTP:
Regular expressions can be used in QTP for identifying objects and text strings with varying values.
Where we use:
1. Defining the property values of an object in Descriptive programming for handling dynamic
objects
2.For parameterizing a step
3. creating checkpoints with varying values
Using Regular Expressions in QTP:
Test for a pattern within a string.
To check for existence of substring in a string. For example, you can test an input string to see if a
telephone number pattern or a credit card number pattern occurs within the string. This is called data
validation.
Replace text.
To find and replace a string with another string. You can use a regular expression to identify specific
text in a document and either remove it completely or replace it with other text.
Extract a substring from a string based upon a pattern match.
To get a string based on pattern match. You want all the words starting with A from a document,
In this case you will use regular expression which will create pattern match and will return all words
starting with A.
We can define a regular expression for a constant value, a Data Table parameter value, an Environment
parameter value, or a property value in Descriptive programming.
QUALITY THOUGHT QTP-MATERIAL

Page 60 of 93


We can define a regular expression in standard checkpoint to verify the property values of an object; we
can set the expected value of an object's property as a regular expression so that an object with a varying
value can be verified.

We can define the text string as a regular expression, when creating a text checkpoint to check that a
varying text string is displayed on our application,
For XML checkpoints we can set attribute or element values as regular expressions.

Ways of Regular Expressions:

a) Backslash Character:

A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate
that the next character be treated as a literal character.
Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be
treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character.

b) Matching Any Single Character:

A period (.) instructs QTP to search for any single character (except for \n).
Ex:
welcome.
Matches welcomes, welcomed, or welcome followed by a space or any other single character.
c) Matching Any Single Character in a List:
Square brackets instruct QTP to search for any single character within a list of characters.
Ex:
To search for the date 1867, 1868, or 1869, enter:
186[789]
d) Matching Any Single Character Not in a List:
When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in
the list except for the ones specified in the string.
Example:
[^ab]
Matches any character except a or b.
e) Matching Any Single Character within a Range:
To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character.
Example:
For matching any year in the 2010s, enter:
201[0-9]
QUALITY THOUGHT QTP-MATERIAL

Page 61 of 93

f) Matching Zero or More Specific Characters:
An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character.
For example:
ca*r
Matches car, caaaaaar, and cr
g) Matching One or More Specific Characters:

A plus sign (+) instructs QTP to match one or more occurrences of the preceding character.
For example:
ca+r
Matches car and caaaaaar, but not cr.
h) Matching Zero or One Specific Character:
A question mark (?) instructs QTP to match zero or one occurrences of the preceding character.
For example:
ca?r
Matches car and cr, but nothing else.
i) Grouping Regular Expressions:
Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and
programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation
operator ( | ) or a repetition operator ( * , + , ? , { } ).
j) Matching One of Several Regular Expressions:
A vertical line (|) instructs QTP to match one of a choice of expressions.
k) Matching the Beginning of a Line:
A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character.
l) Matching the End of a Line:
A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline
character.
m) Matching Any AlphaNumeric Character Including the Underscore:
\w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 0-9, _).
n) Matching Any Non-AlphaNumeric Character:
\W instructs QTP to match any character other than alphanumeric characters and underscores.
o) Combining Regular Expression Operators:
QUALITY THOUGHT QTP-MATERIAL

Page 62 of 93

We can combine regular expression operators in a single expression to achieve the exact search criteria
we need.
For example,
start.*
Matches start, started, starting, starter, and so forth.
we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric
characters.
For example:
[a-zA-Z]*
To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4
digits between 1000-1200.
The regular expression below matches any number between 0 and 1200.
([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)

Regular Expressions has 3 properties
1. Global
2. pattern
3. Ingnore case
Regular Expressions has 3 methods
1. Execute
2. Test
3. Replace
A regular expression is a string that describes or matches a set of strings. It is often called a pattern as it
describes set of strings.
Regular Expression Characters
The below table contains the complete list of regular expression characters and behavior of them.
Character Description
\ Marks the next character as either a special character or a literal. For
example, "n" matches the character "n". "\n" matches a newline character.
The sequence "\\" matches "\" and "\(" matches "(".
^ Matches the beginning of input.
$ Matches the end of input.
* Matches the preceding character zero or more times. For example, "zo*"
matches either "z" or "zoo".
QUALITY THOUGHT QTP-MATERIAL

Page 63 of 93

+ Matches the preceding character one or more times. For example, "zo+"
matches "zoo" but not "z".
? Matches the preceding character zero or one time. For example, "a?ve?"
matches the "ve" in "never".
. Matches any single character except a newline character.
(pattern) Matches pattern and remembers the match. The matched substring can be
retrieved from the resulting Matches collection, using Item [0]...[n]. To
match parentheses characters ( ), use "\(" or "\)".
x|y Matches either x or y. For example, "z|wood" matches "z" or "wood".
"(z|w)oo" matches "zoo" or "wood".
{n} n is a nonnegative integer. Matches exactly n times. For example, "o{2}"
does not match the "o" in "Bob," but matches the first two o's in
"foooood".
{n,} n is a nonnegative integer. Matches at least n times. For example, "o{2,}"
does not match the "o" in "Bob" and matches all the o's in "foooood."
"o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{n,m} m and n are nonnegative integers. Matches at least n and at most m times.
For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}"
is equivalent to "o?".
[xyz] A character set. Matches any one of the enclosed characters. For example,
"[abc]" matches the "a" in "plain".
[^xyz] A negative character set. Matches any character not enclosed. For
example, "[^abc]" matches the "p" in "plain".
[a-z] A range of characters. Matches any character in the specified range. For
example, "[a-z]" matches any lowercase alphabetic character in the range
"a" through "z".
[^m-z] A negative range characters. Matches any character not in the specified
range. For example, "[m-z]" matches any character not in the range "m"
through "z".
\b Matches a word boundary, that is, the position between a word and a
space. For example, "er\b" matches the "er" in "never" but not the "er" in
"verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never
early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a non-digit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any white space including space, tab, form-feed, etc. Equivalent
to "[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore. Equivalent to "[A-Za-
z0-9_]".
\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\num Matches num, where num is a positive integer. A reference back to
remembered matches. For example, "(.)\1" matches two consecutive
identical characters.
QUALITY THOUGHT QTP-MATERIAL

Page 64 of 93

\n Matches n, where n is an octal escape value. Octal escape values must be
1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab
character. "\0011" is the equivalent of "\001" & "1". Octal escape values
must not exceed 256. If they do, only the first two digits comprise the
expression. Allows ASCII codes to be used in regular expressions.
\xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape
values must be exactly two digits long. For example, "\x41" matches "A".
"\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in
regular expressions.

We can extend a regular expression by combining or grouping multiple regular expression operators. In
this case we should follow the order of precedence.
Order of Precedence
Regular expressions are interpreted from left to right. The order of precedence when building a Regular
Expressions is
Order Operator(s) Description
1 \ Escape
2 (), (?:), (?=), [] Parentheses and Brackets
3 *, +, ?, {n}, {n,}, {n,m} Quantifiers
4 ^, $, \anymetacharacter Anchors and Sequences
5 | Alternation
Escape (\)
There are so many special characters in regular expressions. I have to verify 2*2=4 is available in the
main text. For that I have to specify regular expression pattern as 2*2=4. But * will work like a
regular expression and the verification will get fail. In this case the * should be considered as a literal
character instead regular expression.
Back Slash (\) character is useful to treat a special character as a literal character. Provide the Back Slash
(\) character in precede of special characters which you want to treat as literal character.
In the above situation we should use 2\*2=4 in the pattern.
List of Special Characters in Regular Expressions
$ , ( , ) , * , + , . , [ , ] , ? , \ , ^ , { , |

Parentheses ( () )
Parentheses used to group the matches.
Brackets ([])
QUALITY THOUGHT QTP-MATERIAL

Page 65 of 93

You can create a list of matching characters by placing one or more individual characters within square
brackets ([]). When characters are enclosed in brackets, the list is called a bracket expression. Within
brackets, as anywhere else, ordinary characters represent themselves, that is, they match an occurrence of
themselves in the input text. Most special characters lose their meaning when they occur inside a bracket
expression.
Parentheses and Brackets will be explained detailed in Alternation.
Quantifiers
Quantifiers are used to specify the number of occurrences to match against or when we dont have the
quantity of the characters are there to match.
Ex:
If we need to match a word Zoooo then we should write regular expression like Zo{4}. 4 indicate the
number of os in the word Zoooo.
Suppose we dont know how many times o exist in the word, but we expect at least two os should
available in the word. Then the regular expression will be like this Zo{2,}
Here {2,} tells that at least two times the character should exist.
List of Quantifiers
*, + , ? , {n} , {n,} , {n,m}
Anchors
Anchors do not match any characters. They match a position. These are used to specify which part of the
string should be matched. The part is either beginning or end of a line or word.
Ex:
If we are verifying the word QTP is starting with Q or not then we use regular expression like ^Q.
Here carot (^) is not matching the character Q but it is matching the position of Q. Thats
what Anchors do.
List of Anchors
^ , $ , \b , \B
Alternation ( | )
Alternation allows us to use a choice between two or more matches. It can be used to match a single
regular expression out of several possible regular expressions.
Ex:
The below Regular Expression is to match a Date.
QUALITY THOUGHT QTP-MATERIAL

Page 66 of 93

Format: MM/DD/YYYY

MM: (0[1-9]|1[0-2])
Min month number is 1 and Max Month number is 12

DD: (0[1-9]|1[0-9]|2[0-9]|3[0-1])
Min Date number is 1 and Max Month number is 31

YYYY: ([0-9][0-9][0-9][1-9]|[1-9]000|[1-9][1-9]00|[1-9][1-9][1-9]0)
Min Year number is 1 and Max Year number is 9999 (Assume)
In the above regular expression we have used Parentheses, Brackets and Alternation.
Brackets used to match values between the specified ranges. 0[1-9] means, this expression should match
numbers from01 to 09.
Alternation used to match a single regular expression from the specified regular expression matches. 0[1-
9]|1[0-2]means, use any one of the regular expression to match.
Parentheses used to group all regular expression matches. (0[1-9]|1[0-2]) means, use any one of the
regular expression to match from this Group.

Scripting Regular Expressions
From VBScript 5.0 Microsoft provided facility to use Regular Expressions in Scripting Techniques.
By using this we can write scripts to Test for a pattern within a string, to replace text and to extract a
substring from a string based upon a pattern match.
Using Regular Expressions in Scripting Techniques
'To use Regular Expressions in scripting first we should create Instance of Regular Expression Class.
Set SampleRegExP = New RegExp

'Set the Search Pattern (Regular Expression)
SampleRegExP.Pattern= H.*

'Specify the Case Sensitivity is true or false
SampleRegExP.IgnoreCase= False

'Specify required search results (True is for all search Results, False is for only one)
SampleRegExP.Global=True

'Execute Search conditions on a main string
QUALITY THOUGHT QTP-MATERIAL

Page 67 of 93

Set Matches = SampleRegExP.Execute(Hi How Are You)

'Get the results by using a For Loop
For Each Match in Matches
Msgbox Match.FirstIndex
Msgbox Match.Value
Next
'Script to extract a substring from a string based upon a pattern match.
'************************************************

rExpression="H."
MainString="Hi How Are You"

Set SampleRegExP = New RegExp
SampleRegExP.Pattern= rExpression
SampleRegExP.IgnoreCase= False
SampleRegExP.Global=True

Set Matches = SampleRegExP.Execute(MainString)

For Each Match in Matches
Msgbox Match.FirstIndex
Msgbox Match.Value
Next
'************************************************
'************************************************
'Script to Replace string
'************************************************

rExpression="H."
MainString="Hi How Are You"
ReplacedString= "Hello"

Set SampleRegExP = New RegExp
SampleRegExP.Pattern= rExpression
SampleRegExP.IgnoreCase= False
SampleRegExP.Global=True

Msgbox SampleRegExP.Replace (MainString,ReplacedString)
'************************************************
'Script to Test a string existence
rExpression="H."
MainString="Hi How Are You"
QUALITY THOUGHT QTP-MATERIAL

Page 68 of 93

Set SampleRegExP = New RegExp
SampleRegExP.Pattern= rExpression
SampleRegExP.IgnoreCase= False
SampleRegExP.Global=True
retVal = SampleRegExP.Test(MainString)
If retVal Then
Msgbox "One or more matches were found."
Else
Msgbox "No match was found."
End If
'************************************************
Error Handling in QTP
Error handling refers to the anticipation, detection, and resolution of programming, application, and
communications errors.
Within every Script we have to think about possible exceptions and how to handle them. Especially in the
uppermost layers of the script, it is important to handle all exceptions.
In QTP you have handled the Error Exceptions in the following ways
1) In QTP Run Settings
2) In VbScript (On Error statements)
3) Recovery Scenarios
4) Through conditional coding in Test Script

1) In QTP Run Settings
Goto File > Settings > Run > when errors occurring during run session
Choose one option in the drop down when error occurring during run session. It will use to prevent Errors
during run session
QUALITY THOUGHT QTP-MATERIAL

Page 69 of 93



2) In VbScript (On Error Statements)
On Error Statements
1. On Error Resume Next
2. On Error Go to 0
3. Error Object
On Error Resume Next:
On Error Resume Next statement enables the Error handling in the code.If there is error in the
code "On error Resume Next" ignores it and continue with next line of code.
Note: With On Error Resume Next error is not corrected, just ignored, and an error
message is not displayed
On Error Go to 0:
On error got to 0 statement disables error handling we have previiously enabled it by using On
Error resume Next.
Error Object
Whenever there is a run-time error in the program, the properties of an Err object are filled with
the information that helps to identify and handle the error.
After an On Error Resume Next statement the Err object's properties are reset to zero or zero-
length strings ("").
Because the Err object is an intrinsic (basic / its part of every vbscript project you create) object
with global scope there is no need to create an instance of it in your code. That is it does not
need to be declared before it can be used.
QUALITY THOUGHT QTP-MATERIAL

Page 70 of 93

Example:
On error resume next

'divide by zero
z=40/0

' Report the error occured. You can see the error number and description in result summary
If Err.number <> 0 then

Reporter.ReportEvent micWarning,"Error Occured","Error number is " & err.number & " and
description is : " & err.description

Clear the error
err.Clear
'disables error handling
on error goto 0

3) Recovery Scenario

Recovery Scenario:

When executing scripts we may get some Unexpected errors.To recover the test and continue
running script from these unexpected errors we use Recovery Scenarios.

A recovery scenario consists of the following:

Trigger Event:

The event that interrupts your run session. For example a window that may pop up on screen.

Recovery Operations:

Properties Purpose
Description Contains a string describing the error.
Number Contains the Error number. It is the default Property, means Err.Number is same as Err
HelpFile Contains path to the help file
HelpContext Its a Context ID within the helpfile. The HelpContext property is used to automatically
display the Help topic identified
Source Contains a string expression that is usually the class name or programmatic ID of the
object that caused the error.
LastDLLError Contains last error code generated by DLL;Available only on 32 bit windows systems.
Methods Purpose
Clear Clears all property settings of the Err object. [VBScript calls the Clear method
automatically whenever any of the following statements is executed:
On Error Resume Next
Exit Sub
Exit Function ]
Raise Forces a run-time error of a given number to be generated.
QUALITY THOUGHT QTP-MATERIAL

Page 71 of 93

The operations to perform to enable QTP to continue running the test after the trigger event
interrupts the run session.
For example, clicking an OK button in a pop-up window.

Post-Recovery Test Run Option:

The instructions on how QTP should proceed after the recovery operations have been performed,
and from which point in the test QTP should continue. For example, you may want to restart a
test from the beginning, or skip a step entirely and continue with the next step in the test.
Recovery scenarios are saved in recovery scenario files having the extension .qrs. A recovery
scenario file is a logical collection of recovery scenarios, grouped according to our specific
requirements.
Trigger Event:
Trigger Event can handle following four events:

1. Pop-up window: To handle unwanted pop ups.

2. Object state: To handle object related errors at runtime.

3. Test run error: To handle vb script statement errors at runtime.

4. Application crash: To handle crashed applications at runtime.


Recovery Operations for Pop-up window:
Steps to navigate to handle the un wanted Pop-up window
Trigger Event:
1) Go to > Resources Menu
2) Select the > Recovery Scenario manger
3) Select the New Scenario button
4) Select the Next button in Recovery Scenario manager window
QUALITY THOUGHT QTP-MATERIAL

Page 72 of 93


5) Trigger event window will appearing


6) Select any one Event in the trigger event window and after selecting click on the Next
Button
7) If you select unwanted Pop-up window as paint the Pop-Up window conditions page will
be appearing
8) Select the hand i-con it will use to capture the title and text values of the pop-
up window like the following picture
QUALITY THOUGHT QTP-MATERIAL

Page 73 of 93



Recovery Operation:
1) After trigger Event operation Recovery Operations window will be appearing

2) Here you must define at least one operation for this pop-up. So press the Next button to
define it. After that Recovery Operation window will appear

3) Select the any one Type of Operation Recovery Operation for the pop-up window after the
click on Next button
QUALITY THOUGHT QTP-MATERIAL

Page 74 of 93

4) Here you have 4 operations for suppose you select the Keyboard or mouse operation you
must have select the Click Button or Press key Recovery operation


5) After Uncheck the Add another recovery operation in the Recovery Operations window

Post Recovery Test Run Option Steps:
1. After Recovery operation Post Recovery Test Run option will appear

QUALITY THOUGHT QTP-MATERIAL

Page 75 of 93

2. Post Recovery Operations are:
a) Repeat current step and continue
b) Proceed to next step
c) Proceed to next action or component iteration
d) Proceed to next test iteration
e) Restart current test run
f) Stop the test run
3. Select Post Recovery Operation and click the Next button
4. Name and Description window will appear. Mention the Scenario Name

5. Click the Next button finish window will appear

6. Select the any one check box Add scenario to current test or Add scenario to default test
settings and clik the finish button
7. Save the Recovery Scenario file with extension of .qrs
Recovery operation for Object state
Trigger event:
1) Goto > Resources Menu > Recovery Scenario Manager > New > Next
QUALITY THOUGHT QTP-MATERIAL

Page 76 of 93

2) Trigger Event window will appear . Select Object state as Trigger event and click on Next
button

3) Select Object window will appear. Click the Hand icon and Select the object.Click
the Next button. Here object hierarchy window displays the object hierarchy.

4) Select Object property with value and click on Next button



QUALITY THOUGHT QTP-MATERIAL

Page 77 of 93

Recovery operation:
Recovery Operation >Select the Recovery operation (key board or mouse, close application
process, Function call, Restart Microsoft window) > Uncheck Add another Recovery Operation --
> Next
Post-Recovery operation:
Post-Recovery Test Run Option (Repeat current step and continue, Proceed to Next step, Proceed
to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run) > Next
> Enter Scenario Name > Next > Select Option Finish > Save the scenario with .qrs.
Recovery Operation for Test run error:
Trigger Event:
1) Goto > Resources Menu > Recovery Scenario Manager > New > Next
2) Trigger Event window will appear. Select Test run error as Trigger event and click on Next

3) Select the Error in Select Test Run error window. Here Error description displays the selected
error object description

4) After selecting the error > Click on Next button

QUALITY THOUGHT QTP-MATERIAL

Page 78 of 93

Recovery Operation:
Recovery Operation >Select the Recovery operation (key board or mouse, close application
process, Function call, Restart Microsoft window) > Uncheck Add another Recovery Operation --
> Next
Post-Recovery operation:
Post-Recovery Test Run Option (Repeat current step and continue, Proceed to Next step, Proceed
to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run) > Next
> Enter Scenario Name > Next > Select Option Finish > Save the scenario with .qrs.
Recovery Operations for Application crash
Trigger event:
1) Goto > Resources Menu > Recovery Scenario Manager > New > Next
2) Trigger Event window will appear. Select Application crash as Trigger event and click on
Next

3) Select the Running processes list in Select processes and click Add button or Click the +
button to enter a processes name and click next button


QUALITY THOUGHT QTP-MATERIAL

Page 79 of 93

Recovery Operation:
Recovery Operation >Select the Recovery operation (key board or mouse, close application
process, Function call, Restart Microsoft window) > Uncheck Add another Recovery Operation --
> Next
Post-Recovery operation:
Post-Recovery Test Run Option (Repeat current step and continue, Proceed to Next step, Proceed
to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run) > Next
> Enter Scenario Name > Next > Select Option Finish > Save the scenario with .qrs.
4) Through Conditional statements:
When error occurred, Report in detail. When working with GUI objects Use Exist statement
It returns the Boolean value so you handle through the Conditional statements Like
IfThenElse.End if and Select case itemcase1case else.End Select
Example:
Val = Browser(Google).Page(Google).webedit(q).Exist
If Val = True Then
Browser(Google).Page(Google).Webedit(q).set quality thought
Else
Reporter.reportevent micfail, Verifing the WebEdit object appearing, The WedEdit
object is not appearing in the web application
End if
Desc$
44riptive Programming:
Descriptive programming is meant for dealing with large group of objects that matches the selection
criteriaCCC.
Entering Objects Information directly into the test script is called descriptive programming.In DP,
we will be "manually"
specifying the properties and values by which the relevant object will be identified. This way
QTP wont search for the properties data in the Object Repository, but will take it from the DP
statement.
Object Spy is used to get the properties and their values to uniquely identify the objects in the
application.
If we know such properties and their unique values that can identify the required object without
ambiguity, we need not use Object Spy.
Two ways of descriptive programming:
1) Static Programming: We provide the set of properties and values that describe the object
directly in a VBScript statement.
QUALITY THOUGHT QTP-MATERIAL

Page 80 of 93

2) Dynamic Programming : We add a collection of properties and values to a Description
CCobject, and then enter the Description object name in the statement
Advantages:
a) Descriptive Programming based Test scripts are faster in execution than Repository based Test
scripts
b) Scripts are portable (we can run these scripts from any machine easily
c) Maintenance is easy (less amount of resources)
d) We can start Test Execution process even though Application is not ready.
e) Descriptive programming is mainly used for web pages like transactional reports of banking
application (or) dealing with broken links of web page where the automation script have to
perform user action/verification based on matching criteria
Which Objects Should be considered for descriptive programming?
It is not good idea to consider a stable object for descriptive programming. It is better to use
Object Repository for stable objects
For the Objects in large group and we need to pick them based on matching criteria. Then go for
Descriptive programming
When to use Descriptive Programming?

Following are some of the Scenarios where Descriptive programming is used:

Scenario #1: Suppose we need to start Automation before Build Release.
OR:- There is no application to create Object Repository.

Scenario #2: If the Application under test is having Dynamic Objects.
OR:- Difficult to handle Dynamic Objects using Object Repository.

Scenario #3: When the application under Test is having objects that are adding in the Run Time.
OR:- We cant add objects to Object Repository in run time.


Scenario #4: If Application under test is having similar type of objects or similar name objects.
OR:- Object Repository will create multiple objects with same description unnecessarily.

Scenario #5: When Application under test have more objects to perform operations.
OR:- The performance will decrease if object repository is having huge number of objects.

Static Programming:
In this style of script generation, we provide objects information directly into the Script
Example1:
Systemutil.Run "iexplore.exe","www.gmail.com"
Browser("name:=Gmail: Email from Google").Page("title:=Gmail: Email from
Google").WebEdit("name:=Email").Set "qualitythought"

Browser("name:=Gmail: Email from Google").Page("title:=Gmail: Email from
Google").WebEdit("name:=Passwd").Set "123456"

Browser("name:=Gmail: Email from Google").Page("title:=Gmail: Email from
Google").WebButton("name:=Sign in").Click

QUALITY THOUGHT QTP-MATERIAL

Page 81 of 93

Note: If we feel one property information is not sufficient for recognizing the object uniquely,
and then we can provide more properties information by separating with commas.
Example2:
Using Regular Expression in Static DP
Browser("title:=Compare term.*").Page("title:=Compare
term.*").WebList("name:=SI").Highlight
Browser("title:=Compare term.*").Page("title:=Compare
term.*").WebList("name:=SI").Select "10 Lacs"

Dynamic Descriptive Programming: Creating Description Objects, Generating Statements using
Description Objects is called Dynamic descriptive Programming
Description Object:
In the Descriptive programming these are two steps to be followed for each of the object you want to
automate
Step1: Create a Object description using description object and then add all identification properties to
the Description object
Step2: Create Object reference using object Description. Once you get the reference of the object, you
can perform user action (or) verification on it Just like the way you do using Object Repository Script
Note: Description is implicit object in QTP which can be used to store the identification properties of
Object and Create a description for an object
Synt ax:
For Creating a description of an UI Object
Dim objDesc
Set objDesc = Description.Create()
This statement will create an empty container to store object unique properties
objDesc(property name1).Value = Actual property value(Use object spy)
objDesc(property name2).Value = Actual property value
Add as many identification properties as need to this object
Note: While Creating description object, use the keyword Set
Web Object and Corresponding properties for Creating description Object
Object Properties
QUALITY THOUGHT QTP-MATERIAL

Page 82 of 93

WebEdit MicClass = WebEdit
name = Name property given by developer
WebList MicClass = WebList
name = Name property given by developer
WebRadioGroup MicClass = WebRadioGroup
name = Name property given by developer
WebCheckbox MicClass = WebCheckBox
name = Name property given by developer
Weblink MicClass = WebList
name = Name property given by developer
WebElement MicClass = WebList
name = Name property given by developer
Image MicClass = WebList
name = Name property given by developer
WebButton MicClass = WebButton
name = Name property given by developer

Example:
For browser and Page Objects
Dim Br, Pg
Set Br = Description.Create()
Br(MicClass).Vlaue = Browser
Br(name).Value = Developer given name
Set Pg = Description.Create()
Pg(MicClass).Value = Page
Pg(title).Vlaue = developer given title
For WebEdit Object:
Dim objDesc,objRef,val
Set objDesc = Description.Create()
objDesc(MicClass).Vlaue = WebEdit
objDesc(name).Value = developer given name
Set objRef = Browser(Br).Page(Pg).WebEdit(objDesc)
For User Action
objRef.Highlight
QUALITY THOUGHT QTP-MATERIAL

Page 83 of 93

objRef.Set Quality thought
For Verification
Val = objref.GetRoproperty(value)
Msgbox val
For WebList Object:
Dim ObjDesc,ObjRef
Set ObjDesc = Description.Create()
ObjDesc(MicClass).Value = WebList
ObjDesc(Name).Value = developer given name
Set ObjRef = Browser(br).Page(pg).WebList(ObjDesc)
For user Action
ObjRef.Select <index> or ObjRef.Select <string>
For Verification
Val = ObjRef.GetRoproperty(value)
Similarly any Other UI objects can be Created as the same way mentioned above.
Understanding ChildObjects Method:
This method is available at page level and at webtable level. In Both Cases, this method expects input as
Description Object of an objects group matching some criteria
This function returns a collection of objects matching the criteria passed to this function
Syntax:
Set objCollection = Browser(br).Page(pg).ChildObjects(<Object Description>)





QUALITY THOUGHT QTP-MATERIAL

Page 84 of 93



The bellow fig shows the Objects collection








Note: The object collection object can be used similar to array
Example:
For Broken link examples we will create description of link object, Collect all the links and read the href
property of link. If href is empty it means developer didnt set the link and hence it is broken link
Dim Objdesc, Objref, Objcollection, noOflinks, href
Create Description object matching criteria
Set Objdesc = Description.Create()
Objdesc(MicClass).Value = link
Set Objcollection = Browser(br).page(pg).Childobjecs(Objdesc)
This statement will return the number of objects in collection
noOflinks = Objcollection.count
msgbox Total number of links appearing on this page&noOflinks
For counter = 0 to (noOflinks-1)
Set Objref = Objcollection(counter)
innertext = Objref.GetRoproperty(innertext)
href = Objref.GetRoproperty(href)









Object
Collection
0 Obj name1
1 Obj name 2
2 Obj name 3
3 .
. .
. .
. .
. .
N Nth obj Name
QUALITY THOUGHT QTP-MATERIAL

Page 85 of 93

href = trim(href)
If href = then
Reporter.Reportevent Micfail,verify link&innertext, The link&innertext& is
broken
Else
Reporter.Reportevent Micpass,verify link&innertext, The
link&innertext& is working fine
End if
Web Table
What is a web table object?
Tables are one of the primary design tools for HTML documents. Tables allow for greater control over
page layout, allowing creation of more visually interesting pages. Tables are also used to set apart
sections of documents, such as in sidebars, navigation bars, or framing images and their titles and
captions. Tables have literally changed the look of the Web page. Originally, tables let people present
data in a column format. Designers quickly figured out ways to improve the layout of their pages using
tables.

A Sample Web Table Object


Every web table contains data (text data) and child objects in specified cells. When we are working with
descriptive programming using QTP, web table object is very useful to get data or to get object
information for further activities.

For Web table Row number starts from 1 and column number starts from 1
As we moving down the web table across a column, the row number will change(increment by 1),
but column number is fixed
As we move horizontally in web tables across a row, the column number will change (increment
by 1), but row number is fixed
QUALITY THOUGHT QTP-MATERIAL

Page 86 of 93

Each of cell of web table contains both row number and column number when we represent a cell
in automation script, we should use both row number and column number as identification of cell.
Note: Web tables normally defined with zero border line. That means they are present but not
visible on web page.
Web developers/UI designers place the UI elements in Cells of web table to bring the presentation
layer (web page) max utilization and good appearance
Child Item method
The Child Item method will give you the reference of a UI object residing in Webtable cell
Inputs to this function
Row number, column number of the Cell
Mic-Class of UI object
Index of UI object- This is index of then an UI object type
Accessing Child Objects from web table Cell
rCount=Browser(br).Page(pg).WebTable(WTname).RowCount
For r=1 to rCount
cCount=Browser(br).Page(pg).WebTable(WTname).ColumnCount(r)
For c=1 to cCount
oCount=Browser(br).Page(pg).WebTable(WTname).ChildItemCount(r,c,"Obj name")
For obj=0 to oCount-1
set cObject= Browser(br).Page(pg).WebTable(WTname).ChildItem(r,c,objname,obj)
msgbox cObject.getROproperty("html id")
Next
Next
Next
Difference between childobject, childitem and Getcelldata methods
ChildObjects method is to access total child objects from web table object using description object.
Syntax: - object. ChildObjects ([Description])

ChildItem method is to access child objects from a web table cell in web table object without using
description object.
Syntax:-object. ChildItem (Row, Column, MicClass, Index)

Getcelldata method is to retrieve data from a web table cell in web table object.
Syntax: - object. Getcelldata (Row, Column)





QUALITY THOUGHT QTP-MATERIAL

Page 87 of 93


Excel Handling
We have passed the test data into automation script either directly in script or variable or external data
source.

Auto code
+
Test Data
Br().Pg().
weblist().
Select
Auto code + Variable
Dim X
X = Some value
Br().Pg().Weblist().
Select X
Variable
Dim X
X = Data from External source file
Externalsource value
Some
value

Automation
Br().Pg().Weblist().
Select X

Why we maintain Test data outside the automation script?
Automation Scripts Execution(during regression) is usually done by non-technical employees like ---
manual testers, low cost working team bank employees like tellers or collateral analyst.
When they have to change the test data, their technical skills are not adequate to modify the scripts.
Hence, they are not allowed to change the test data inside the automation script. So separating test data
from automation script is only solution for this problem

Simple object model Example:
Excel Application --> Workbooks--> Worksheet--> cells
Workbook It is actual excel file that you see in windows directory
Active workbook A work book that is opened is called active work book
Worksheet Is like a page in book. It contains cells that can store data
Cell Is the leaf level element in excel file. This is the one that holds the data
QUALITY THOUGHT QTP-MATERIAL

Page 88 of 93

NOTE: The Class for handling excel file is not part of QTP-VbScript , We need to get the reference of
excel file handler/Excel application using the function ----CreateObject
Steps for accessing Excel file data
Create Reference of classExcel.Application
With reference, Open the work book
Once work book opened, get the reference of work sheet
With reference of work sheet, set/get the cell data
Save the opened work book
Close the [workbook] Excel reference
Create an Excel File:
'Create a new Microsoft Excel object
Set myxl = createobject("excel.application")

'To make Excel visible
myxl.Application.Visible = true

myxl.Workbooks.Add
wait 2

'Save the Excel file as qtp.xls
myxl.ActiveWorkbook.SaveAs "D:\qtp.xls"

'close Excel
myxl.Application.Quit

Set myxl=nothing
Create an Excel File , Enter some data , Save the Excel and close the Excel:
Set myxl = createobject("excel.application")

'Make sure that you have created an excel file before exeuting the script.
'Use the path of excel file in the below code
'Also make sure that your excel file is in Closed state before exeuting the script.

myxl.Workbooks.Open "D:\qtp.xls"
myxl.Application.Visible = true

'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered
set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1")

'Enter values in Sheet1.
'The format of entering values in Excel is excelSheet.Cells(row,column)=value
mysheet.cells(1,1).value ="Name"
mysheet.cells(1,2).value ="Age"
mysheet.cells(2,1).value ="Ram"
QUALITY THOUGHT QTP-MATERIAL

Page 89 of 93

mysheet.cells(2,2).value ="20"
mysheet.cells(3,1).value ="Raghu"
mysheet.cells(3,2).value ="15"

'Save the Workbook
Read the data from Excel File:
Set myxl = createobject("excel.application")

'Make sure that you have created an excel file before exeuting the script.
'Use the path of excel file in the below code
'Also make sure that your excel file is in Closed state
myxl.Workbooks.Open "D:\qtp.xls"

myxl.Application.Visible = true

'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered
set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1")

'Get the max row occupied in the excel file
Row=mysheet.UsedRange.Rows.Count

'Get the max column occupied in the excel file
Col=mysheet.UsedRange.columns.count

'To read the data from the entire Excel file
For i= 1 to Row
For j=1 to Col
Msgbox mysheet.cells(i,j).value
Next
Next

'Save the Workbook
myxl.ActiveWorkbook.Save

'Close the Workbook
myxl.ActiveWorkbook.Close

'Close Excel
myxl.Application.Quit

Set mysheet =nothing
Set myxl = nothing
Compare Two Excel sheets Cell by cell:
Mismatch=0
Set myxl = createobject("excel.application")

'To make Excel visible
myxl.Visible = True
QUALITY THOUGHT QTP-MATERIAL

Page 90 of 93


'Open a workbook "qtp1.xls"
Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls")

'Open a workbook "qtp2.xls"
Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls")

Set mysheet1=Workbook1.Worksheets("Sheet1")
Set mysheet2=Workbook2.Worksheets("Sheet1")

'Compare two sheets cell by cell
For Each cell In mysheet1.UsedRange

'Highlights the cell if cell values not match
If cell.Value <>mysheet2.Range(cell.Address).Value Then
'Highlights the cell if cell values not match
cell.Interior.ColorIndex = 3
mismatch=1
End If
Next

If Mismatch=0 Then
Msgbox "No Mismach exists"
End If

'close the workbooks
Workbook1.close
Workbook2.close

myxl.Quit
set myxl=nothing
Search for Particular value in Excel:
Set myxl = createobject("excel.application")

'Make sure that you have created an excel file before exeuting the script.
'Use the path of excel file in the below code
'Also make sure that your excel file is in Closed state before executing the script.

myxl.Workbooks.Open "D:\qtp.xls"
myxl.Application.Visible = true

'This is the name of Sheet in Excel file "qtp.xls" where data needs to be entered
set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1")

'Contents of Sheet1
'Name Age
'Ram 20
'Raghu 15
QUALITY THOUGHT QTP-MATERIAL

Page 91 of 93


'Select the used range in particular sheet
With mysheet.UsedRange

' Data "Ram" to search
' Loop through the used range

For each search_data in mysheet.UsedRange

' compare with the expected data
If search_data="Ram" then
'make the cell with color if it finds the data
search_data.Interior.ColorIndex = 40
End If
next
End With

'Save the Workbook
myxl.ActiveWorkbook.Save

'Close the Workbook
myxl.ActiveWorkbook.Close

'Close Excel
myxl.Application.Quit

Set mysheet =nothing
Set myxl = nothing
Copy an Excel sheet to another Excel sheet:
Set myxl = createobject("excel.application")

'To make Excel visible
myxl.Visible = True

'Open a workbook "qtp1.xls"
Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls")

'Open a workbook "qtp2.xls"
Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls")

'Copy the used range of workbook "qtp1.xls"
Workbook1.Worksheets("Sheet1").UsedRange.Copy

'Paste the copied values in above step in the A1 cell of workbook "qtp2.xls"
Workbook2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste =xlValues

'Save the workbooks
Workbook1.save
QUALITY THOUGHT QTP-MATERIAL

Page 92 of 93

Workbook2.save

'close the workbooks
Workbook1.close
Workbook2.close

myxl.Quit
set myxl=nothing

DATA TABLE METHODS
Data Tables plays major role when using Data/Keyword Driven frameworks. It'll be easy to work with
Data tables if we know the methods.We have the following methods in Data Tables.
1) AddSheet: This method is used to add only one new sheet to the run time data table.
Syntax: DataTable.AddSheet "sheet name"
Example: DataTable.AddSheet "quality"
2) DeleteSheet:This method is used to delete a single sheet from run time data table.
Syntax:DataTable.DeleteSheet (sheet id)
Example: DataTable.DeleteSheet (3)
3) GetSheetCount:This method is used to get the number of sheets available in the run time table.
Syntax:DataTable.GetSheetCount
msgbox datatable.GetSheetCount
4) GetRowCount:This method is used to get the number of rows from the run time data table.
Obviously it'll return the longest used column count from the data table.
Syntax:DataTable.GetRowCount
Ex: msgbox datatable.GetRowCount
5) GetSheet: This method is used to return the specific sheet from the run time data table.
Syntax: DataTable.GetSheet(sheet id)
Example: msgbox datatable. GetSheet(1).GetRowCount
6) Value: This method is used to set or get the values from a particular cell of the run time data
table.
Syntax to set data:
DataTable.Value(Parameter_Name,Sheet_Name) = value or variable
DataTable(Parameter_Name,Sheet_Name) = Value
Example: DataTable.Value(5,2)=a
Syntax to get data:
variable = DataTable.Value(Parameter_Name,Sheet_Name)
variable = DataTable.(Parameter_Name,Sheet_Name)
Example: a= DataTable.Value(5,2)
QUALITY THOUGHT QTP-MATERIAL

Page 93 of 93

7) SetCurrentRow:This method is used to set a particular row as current row. By default it's first
row of the 1st sheet.
Syntax:DataTable.SetCurrentRow(rowNumber)
Example: dataTable.SetCurrentRow(3)
dataTable.value(1,1)="Quality thought"
8) SetNextRow:This method is used to set the next row as the new current row after the current
row.
Syntax:DataTable.SetNextRow
Example:DataTable.SetCurrentRow(3)
DataTable.SetNextRow
DataTable.Value(2,1)="Quality thought"
9) SetPrevRow:This method is to set the row before the current row as the current row in the run
time data table.
Syntax:DataTable.SerPrevRow
Example:datatable.SetCurrentRow(3)
datatable.SerPrevRow
datatable.value(1,1)="Quality thought"
10) Import:This method is used to import an Excel file to the run time table.Assume that we have 3
workbooks in the selected file.We can import all 3 worksheets to the run time data table.
Syntax: DataTable.Import "file path"
Example:DataTable.Import "C:\Automation\qtt.xls"
11) ImportSheet: This method is used to import a particular sheet of the selected Excel file to the run
time data table.
Syntax: DataTable.ImportSheet "file path","source sheet", "destination sheet"
Example: datatable.ImportSheet "C:\Automation\qtt1.xls",2,1
12) Export: This method is used to export a copy of the run time data table to a particular location.
Syntax:DataTable.Export "file path".This will export all the sheets from the run time data table.
Example:DataTable.Export "C:\Automation\qtt.xls"
13) ExportSheet: This method is used to export copy of a particular sheet in the run time data table
to a particular location.
Syntax:DataTable.ExportShee "file path","source sheet.
Example:DataTable.Export "C:\Automation\qtt1.xls",3

You might also like