VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 1
QTP 9.2 provides following features:
Mercury Screen Recorder:
Capture your entire run session in a movie clip or capture only the segments with
errors, and then view your movie from the Test Results window.
Dynamic Management of Object Repositories:
Quick Test now has a new Repositories Collection reserved object that you can
use to programmatically manage the set of object repositories that are associated with an
action during a run session.
Object Repository Manager:
You can use the Object Repository Manager to manage all of the shared object
repositories in your organization from one, central location. This includes adding and
defining objects, modifying objects and their descriptions, parameterize test object
property values, maintaining and organizing repositories, and importing and exporting
repositories in XML format.
You can open multiple object repositories at the same time. Each object
repository opens in its own resizable document window. This enables you to compare the
content of the repositories, to copy or move objects from one object repository to another,
and so forth.
Object Repository Merge Tool:
You can use the Object Repository Merge Tool to merge the objects from two
shared object repositories into a single shared object repository. You can also use the
Object Repository Merge Tool to merge objects from the local object repository of one or
more actions or components into a shared object repository.
When you merge objects from two source object repositories, the content is
copied to a new, target object repository, ensuring that the information in the source
repositories remains unchanged.
If any conflicts occur during the merge, for example, if two objects have the same
name and test object class, but different test object descriptions, the relevant objects are
highlighted in the source repositories, and the Resolution Options pane details the
conflict and possible resolutions.
Multiple Object Repositories per Action or Component:
Quick Test provides several options for storing and accessing test objects. You
can store the test objects for each action or component in its corresponding local object
repository, which is unique for each action and component. You can also store test
objects in one or more shared object repositories that can be used in multiple actions and
components. Alternatively, you can use a combination of objects from the local object
repository and one or more shared object repositories. You choose the combination that
matches your testing needs.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 2
XML Object Repository Format:
Quick test now enables you to import and export object repositories from and to
XML format. This enables you to modify object repositories using the XML editor of
your choice and then import them back into Quick Test. You can import and export files
either from and to the file system or a Quality Center project (if Quick Test is connected
to Quality Center).
Functions Library Editor:
Quick Test now has a built-in function library editor, which enables you to create
and edit function libraries containing VBScript functions, subroutines, modules, and so
forth, and then call their functions from your test or component.
Handling Missing Actions and Resources:
Whenever a testing document (test, component, or application area) contains a
resource that cannot be found, Quick Test opens the Missing Resources pane and lists the
missing resource(s). For example, a test may contain an action or a call to an action that
cannot be found; a testing document may use a shared object repository that cannot be
found; or a testing document may use an object repository parameter that does not have a
default value. In all of these cases, Quick Test indicates this in the Missing Resources
pane, enabling you to map a missing resource to an existing one, or remove it from the
testing document, as required.
How can I check if a parameter exists in Data Table or not?
on error resume next
Val=DataTable ("ParamName", dtGlobalSheet)
if err. number<> 0 then
'Parameter does not exist
else
'Parameter exists
end if
How can I check if a checkpoint passes or not?
chk_PassFail = Browser (...).Page (...).WebEdit (...).Check (Checkpoint ("Check1"))
if chk_PassFail then
MsgBox "Check Point passed"
else MsgBox "Check Point failed"
end if
My test fails due to checkpoint failing, Can I validate a checkpoint without my test
failing due to checkpoint failure?
Reporter. Filter = rfDisableAll 'Disables all the reporting stuff
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 3
chk_PassFail = Browser (...).Page (...).WebEdit (...).Check (Checkpoint ("Check1"))
Reporter. Filter = rfEnableAll 'Enable all the reporting stuff
if chk_PassFail then
MsgBox "Check Point passed"
else
MsgBox "Check Point failed"
end if
What is the difference between an Action and a function?
Action is a thing specific to QTP while functions are a generic thing which is a
feature of VB Scripting. Action can have an object repository associated with it while a
function can't. A function is just lines of code with some/none parameters and a single
return value while an action can have more than one output parameters.
Where to use function or action?
Well answer depends on the scenario. If you want to use the OR feature then you
have to go for Action only. If the functionality is not about any automation script i.e. a
function like getting a string between to specific characters, now this is something not
specific to QTP and can be done on pure VB Script, so this should be done in a function
and not an action. Code specific to QTP can also be put into a function using DP.
Decision of using function/action depends on what any one would be comfortable using
in a given situation.
When to use a Recovery Scenario and when to us on error resume next?
Recovery scenarios are used when you cannot predict at what step the error can
occur or when you know that error won't occur in your QTP script but could occur in the
world outside QTP, again the example would be "out of paper", as this error is caused by
printer device driver. "On error resume next" should be used when you know if an error is
expected and dont want to raise it, you may want to have different actions depending
upon the error that occurred. Use err.number & err.description to get more details about
the error.
How to use environment variable?
A simple definition could be... it is a variable which can be used across the reusable
actions and is not limited to one reusable action.
There are two types of environment variables:
1. User-defined
2. Built-in
We can retrieve the value of any environment variable. But we can set the value of only
user-defined environment variables.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 4
To set the value of a user-defined environment variable:
Environment (Variable Name) = NewValue
To retrieve the value of a loaded environment variable:
CurrValue = Environment (VariableName)
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")
How to rename a checkpoint (QTP 9.0)?
Example:
Window ("Notepad").WinEditor ("Edit").Check Checkpoint ("Edit")
in the above example, the user would like to change the name of the Checkpoint object
from "Edit" to something more meaningful.
Note: This functionality is new to QuickTest Professional 9.0.This is not available
for QTP 8.2 and below.
1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object
in Expert View.
2. Select "Checkpoint Properties" from the pop-up menu.
3. In the Name field, enter the new checkpoint name.
4. Click. The name of the checkpoint object will be updated within the script.
Example:
Window ("Notepad").WinEditor ("Edit").Check Checkpoint ("NewCheckPointName")
Note: You must use the QuickTest Professional user interface to change the name of the
checkpoint. If you manually change the name of the checkpoint in the script, QuickTest
Professional will generate an error during replay. The error message will be similar to the
following:
"The "" Checkpoint object was not found in the Object Repository. Check the Object
Repository to confirm that the object exists or to find the correct name for the object."
The Checkpoint object is not a visible object within the object repository, so if you
manually modify the name, you may need to recreate the checkpoint to resolve the error.
What is the lservrc file in QTP?
The lservrc file contains the license codes that have been installed The lservrc file contains the license codes that have been installed. Whenever a
new license is created, the license code is automatically added to this file. The lservrc file
is a text file, with no extension.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 5
File Location:
1) For a Concurrent (Floating) license installation:
Example: C:\Program Files\XYZ Technologies\ABC Server\English\lservrc
2) For a Seat (Stand-alone) license installation
Example:
C:\Program Files\Mercury Interactive\QuickTest Professional\Bin\lservrc
What to do if you are not able to run QTP from quality center?
This is for especially for newbie‘s with QTP.
Check that you have selected Allow other mercury products to run tests and components
from QTP Tools Options Run Tab.
Understanding the Smart Identification Process
If QuickTest activates the Smart Identification mechanism during a run session (because
it was unable to identify an object based on its learned description), it follows the
following process to identify the object:
1. QuickTest "forgets" the learned test object description and creates a new object
candidate list containing the objects (within the object's parent object) that match all of
the properties defined in the Base Filter Properties list.
2. QuickTest filters out any object in the object candidate list that does not match the first
property listed in the Optional Filter Properties list. The remaining objects become the
new object candidate list.
Walking Through a Smart Identification Example
The following example walks you through the object identification process for an
object. Suppose you have the following statement in your test or component:
Browser("Mercury Tours").Page("Mercury Tours").Image("Login").Click 22,17
When you created your test or component, QuickTest learned the following object
description for the Login image:
However, at some point after you created your test or component, a second login button
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 6
(for logging into the VIP section of the Web site) was added to the page, so the Web
designer changed the original Login button's alt tag to: basic login.
The default description for Web Image objects (alt, html tag, image type) works for most
images in your site, but it no longer works for the Login image, because that image's alt
property no longer matches the learned description. Therefore, when you run your test or
component, QuickTest is unable to identify the Login button based on the learned
description. However, QuickTest succeeds in identifying the Login button using its Smart
Identification definition.
The explanation below describes the process that QuickTest uses to find the Login object
using Smart Identification:
1. According to the Smart Identification definition for Web image objects, QuickTest
learned the values of the following properties when you recorded the click on the Login
image:
2. QuickTest begins the Smart Identification process by identifying the five objects on the
Mercury Tours page that match the base filter properties definition (html tag = INPUT
and image type = Image Button). QuickTest considers these to be the object candidates
and begins checking the object candidates against the Optional Filter Properties list.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 7
3. QuickTest checks the alt property of each of the object candidates, but none have the
alt value: Login, so QuickTest ignores this property and moves on to the next one.
4. QuickTest checks the name property of each of the object candidates, and finds that
two of the objects (both the basic and VIP Login buttons) have the name: login.
QuickTest filters out the other three objects from the list, and these two login buttons
become the new object candidates.
5. QuickTest checks the file name property of the two remaining object candidates. Only
one of them has the file name login.gif, so QuickTest correctly concludes that it has
found the Login button and clicks it.
Step-by-Step Instructions for Configuring a Smart Identification Definition
you use the Smart Identification Properties dialog box, accessible from the Object
Identification dialog box, to configure the Smart Identification definition for a test object
class.
To configure Smart Identification properties: 1. Choose Tools > Object Identification. The Object Identification dialog box opens.
2. Select the appropriate environment in the Environment list. The test object classes
associated with the selected environment are displayed in the Test object classes list.
Note: The environments included in the Environment list are those that correspond to the
loaded add-in environments.
3. Select the test object class you want to configure.
4. Click the Configure button next to the Enable Smart Identification check box. The
Configure button is enabled only when the Enable Smart Identification option is selected.
The Smart Identification Properties dialog box opens:
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 8
5. In the Base Filter Properties list, click Add/Remove. The Add/Remove Properties
dialog box for base filter properties opens.
6. Select the properties you want to include in the Base Filter Properties list and/or clear
the properties you want to remove from the list.
Tip: You can also add property names to the set of available properties for Web objects
using the attribute/ notation. To do this, click New. The New Property dialog box opens.
Enter a valid property in the format attribute/ and click OK. The new property is added to
the Base Filter Properties list. For example, to add a property called MyColor, enter
attribute/MyColor.
7. Click OK to close the Add/Remove Properties dialog box. The updated set of base
filter properties is displayed in the Base Filter Properties list.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 9
8. In the Optional Filter Properties list, click Add/Remove. The Add/Remove Properties
dialog box for optional filter properties opens.
9. Select the properties you want to include in the Optional Filter Properties list and/or
clear the properties you want to remove from the list.
Note: You cannot include the same property in both the base and optional property lists.
You can specify a new property by clicking New and specifying a valid property name in
the displayed dialog box.
Tip: You can also add property names to the set of available properties for Web objects
using the attribute/ notation. To do this, click New. The New Property dialog box opens.
Enter a valid property in the format attribute/ and click OK. The new property is added to
the Optional Filter Properties list. For example, to add a property called MyColor, enter
attribute/MyColor.
10. Click OK to close the Add/Remove Properties dialog box. The properties are
displayed in the Optional Filter Properties list.
11. Use the up and down arrows to set your preferred order for the optional filter
properties. When QuickTest uses the Smart Identification mechanism, it checks the
remaining object candidates against the optional properties one-by-one according to the
order you set in the Optional Filter Properties list until it filters the object candidates
down to one object.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 10
How to verify that the Siebel Test Automation module is installed?
Check that the list of running processes in the Windows Task Manager includes a process
named SiebelAx_Test_A. This process will appear only after you have logged into the
Siebel application.
Does Mercury QTP care what mode the Siebel application is in (HI vs. SI)?
Support for High Interactivity applications is different from support for Standard
Interactivity applications. When recording a script against a HI application, the script
mostly contains calls into the Siebel-provided test automation API. In contrast, when
recording a script against a pure SI application or against a SI component that is
embedded within an HI application (e.g. customer dashboard, query assistant, search
center), the script mostly contains calls that use Mercury‘s native scripting syntax.
Descriptive Programming:
Whenever QTP records any action on any object of an application, it adds some
description on how to recognize that object to a repository of objects called object
repository. QTP cannot take action on an object until unless its object description is in the
Object Repository. But descriptive programming provides a way to perform action on
objects which are not in Object repository
Object Identification:
To identify an object during the play back of the scripts QTP stores some properties
which helps QTP to uniquely identify the object on a page. Below screen shots shows an
example Object repository:
Now to recognize a radio button on a page QTP had added 2 properties the name
of the radio button and the html tag for it. The name the left tree view is the logical name
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 11
given by QTP for the object. This can be changed as per the convenience of the person
writing the test case. QTP only allows UNIQUE logical name under same level of
hierarchy. As we see in the snapshot the two objects in Browser->Page node are
―WebTable‖ and ―testPath‖, they cannot have the same logical name. But an object under
some other node can have the same name. Now with the current repository that we have,
we can only write operation on objects which are in the repository. Some of the example
operations are given below
Browser("Browser").Page("Page").WebRadioGroup ("testPath").Select "2"
CellData = Browser("Browser").Page("Page").WebTable ("WebTable").GetCellData
(1,1)
Browser("Example2").Page("Page").WebEdit("testPath").Set "Test text"
When and Why to use Descriptive programming?
Below are some of the situations when Descriptive Programming can be considered
useful:
1. The objects in the application are dynamic in nature and need special handling to
identify the object. The best example would be of clicking a link which changes
according to the user of the application, Ex. ―Logout <>‖.
2. When object repository is getting huge due to the no. of objects being added. If the size
of Object repository increases too much then it decreases the performance of QTP while
recognizing an object.
3. When you don‘t want to use object repository at all. Well the first question would be
why not Object repository? Consider the following scenario which would help
understand why not Object repository
Scenario 1: Suppose we have a web application that has not been developed yet.Now
QTP for recording the script and adding the objects to repository needs the application to
be up, that would mean waiting for the application to be deployed before we can start of
with making QTP scripts. But if we know the descriptions of the objects that will be
created then we can still start off with the script writing for testing
Scenario 2: Suppose an application has 3 navigation buttons on each and every page.
Let the buttons be ―Cancel‖, ―Back‖ and ―Next‖. Now recording action on these buttons
would add 3 objects per page in the repository. For a 10 page flow this would mean 30
objects which could have been represented just by using 3 objects. So instead of adding
these 30 objects to the repository we can just write 3 descriptions for the object and use it
on any page.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 12
4. Modification to a test case is needed but the Object repository for the same is Read
only or in shared mode i.e. changes may affect other scripts as well.
5. When you want to take action on similar type of object i.e. suppose we have 20
textboxes on the page and there names are in the form txt_1, txt_2, txt_3 and so on. Now
adding all 20 the Object repository would not be a good programming approach.
How to use Descriptive Programming?
There are two ways in which descriptive programming can be used
1. By creating properties collection object for the description.
2. By giving the description in form of the string arguments.
1. By creating properties collection object for the description.
To use this method you need first to create an empty description
Dim obj_Desc ‗Not necessary to declare
Set obj_Desc = Description.Create
Now we have a blank description in ―obj_Desc‖. Each description has 3 properties
―Name‖, ―Value‖ and ―RegularExpression‖.
obj_Desc(―html tag‖).value= ―INPUT‖
When you use a property name for the first time the property is added to the collection
and when you use it again the property is modified. By default each property that is
defined is a regular expression. Suppose if we have the following description
obj_Desc (―html tag‖).value= ―INPUT‖
obj_Desc (―name‖).value= ―txt.*‖
This would mean an object with html tag as INPUT and name starting with txt. Now
actually that ―.*‖ was considered as regular expression. So, if you want the property
―name‖ not to be recognized as a regular expression then you need to set the ―regular
expression‖ property as FALSE
obj_Desc(―html tag‖).value= ―INPUT‖
obj_Desc(―name‖).value= ―txt.*‖
obj_Desc(―name‖).regularexpression= ―txt.*‖
This is how we create a description. Now below is the way we can use it
Browser(―Browser‖).Page(―Page‖).WebEdit(obj_Desc).set ―Test‖
When we say .WebEdit(obj_Desc) we define one more property for our description that
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 13
was not earlier defined that is it‘s a text box (because QTPs WebEdit boxes map to text
boxes in a web page).
If we know that we have more than 1 element with same description on the page then we
must define ―index‖ property for the that description
Now the html code has two objects with same description. So distinguish between these 2
objects we will use the ―index‖ property. Here is the description for both the object
For 1st textbox:
obj_Desc(―html tag‖).value= ―INPUT‖
obj_Desc(―name‖).value= ―txt_Name‖
obj_Desc(―index‖).value= ―0‖
For 2nd textbox:
obj_Desc(―html tag‖).value= ―INPUT‖
obj_Desc(―name‖).value= ―txt_Name‖
obj_Desc(―index‖).value= ―1‖
We can use the same description for both the objects and still distinguish between both of
them
obj_Desc(―html tag‖).value= ―INPUT‖
obj_Desc(―name‖).value= ―txt_Name‖
When I want to refer to the textbox then I will use the inside a WebEdit object and to
refer to the radio button I will use the description object with the WebRadioGroup object.
Browser(―Browser‖).Page(―Page‖).WebEdit(obj_Desc).set ―Test‖ ‗Refers to the text box
Browser(―Browser‖).Page(―Page‖).WebRadioGroup(obj_Desc).set ―Test‖ ‗Refers to the
radio button
But if we use WebElement object for the description then we must define the ―index‖
property because for a webelement the current description would return two objects.
Hierarchy of test description:
When using programmatic descriptions from a specific point within a test object
hierarchy, you must continue to use programmatic descriptions
from that point onward within the same statement. If you specify a test object by its
object repository name after other objects in the hierarchy have
been described using programmatic descriptions, QuickTest cannot identify the object.
For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), since it uses
programmatic descriptions throughout the entire test object hierarchy.
You can also use Browser("Index").Page(Desc1).Link(desc3), since it uses programmatic
descriptions from a certain point in the description (starting
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 14
from the Page object description).
However, you cannot use Browser(Desc1).Page(Desc1).Link("Example1"), since it uses
programmatic descriptions for the Browser and Page objects but
then attempts to use an object repository name for the Link test object (QuickTest tries to
locate the Link object based on its name, but cannot
locate it in the repository because the parent objects were specified using programmatic
descriptions).
Getting Child Object:
We can use description object to get all the objects on the page that matches that specific
description. Suppose we have to check all the checkboxes present on a web page. So we
will first create an object description for a checkboxe and then get all the checkboxes
from the page
Dim obj_ChkDesc
Set obj_ChkDesc=Description.Create
obj_ChkDesc(―html tag‖).value = ―INPUT‖
obj_ChkDesc(―type‖).value = ―checkbox‖
Dim allCheckboxes, singleCheckBox
Set allCheckboxes = Browse(―Browser‖).Page(―Page‖).ChildObjects(obj_ChkDesc)
For each singleCheckBox in allCheckboxes
singleCheckBox.Set ―ON‖
Next
The above code will check all the check boxes present on the page. To get all the child
objects we need to specify an object description i.e. we can‘t use the string arguments
that will be discussed later in the 2nd way of using the programming description.
Possible Operation on Description Object
Consider the below code for all the solutions
Dim obj_ChkDesc
Set obj_ChkDesc=Description.Create
obj_ChkDesc(―html tag‖).value = ―INPUT‖
obj_ChkDesc(―type‖).value = ―checkbox‖
Q: How to get the no. of description defined in a collection
A: obj_ChkDesc.Count ‗Will return 2 in our case
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 15
Q: How to remove a description from the collection
A: obj_ChkDesc.remove ―html tag‖ ‗would delete the html tag property from the
collection
Q: How do I check if property exists or not in the collection?
A: The answer is that it‘s not possible. Because whenever we try to access a property
which is not defined its automatically added to the collection. The only way to determine
is to check its value that is use an if statement ―if obj_ChkDesc(―html tag‖).value =
empty then‖.
2. By giving the description in form of the string arguments.
This is a more commonly used method for Descriptive Programming.
You can describe an object directly in a statement by specifying property:=value pairs
describing the object instead of specifying an object‘s name.
The general syntax is:
TestObject("PropertyName1:=PropertyValue1", "..." ,
"PropertyNameX:=PropertyValueX")
TestObject—the test object class could be WebEdit, WebRadioGroup etc….
Browser(―Browser‖).Page(―Page‖).WebRadioGroup(―Name:=txt_Name‖,‖html
tag:=INPUT‖).set ―Test‖
If we refer to them as a web element then we will have to distinguish between the 2 using
the index property
Browser(―Browser‖).Page(―Page‖).WebElement(―Name:=txt_Name‖,‖html
tag:=INPUT‖,‖Index:=0‖).set ―Test‖ ‗ Refers to the textbox
Browser(―Browser‖).Page(―Page‖).WebElement(―Name:=txt_Name‖,‖html
tag:=INPUT‖,‖Index:=1‖).set ―Test‖ ‗ Refers to the radio button
Four different ways to launch your application are mentioned below:
SystemUtil.Run
SystemUtil.Run ( FileName, Parameters, Path, Operation )
FileName - The name of the file you want to run.
Parameters - If the specified FileName is an executable file, use the Parameters
argument to specify any parameters to be passed to the application.
Path - The default directory of the application or file.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 16
Operation - The action to be performed. If this argument is blank (""), the open
operation is performed.
The following operations can be specified for the operation argument of the
SystemUtil.Run method:
Example: SystemUtil.Run ―c:\flight.exe‖
InvokeApplication
InvokeApplication("Full URL as Parameter")
Static and Dynamic Arrays:
VBScript provides flexibility for declaring arrays as static or dynamic.
A static array has a specific number of elements. The size of a static array cannot be
altered at run time.
A dynamic array can be resized at any time. Dynamic arrays are useful when size of the
array cannot be determined. The array size can be changed at run time.
Next we will deal with user defined procedures, functions and subroutines.
I have seen an umpteen no of posts in every QTP group I visited asking about Test
Automation frameworks. Here I would like to collate the useful inputs i received from
various QTP groups and discussion forums.
Data-driven Testing:
Data-driven testing is a framework where test input and output values are read from data
files (datapools, ODBC sources, csv files, Excel files, DAO objects, ADO objects, and
such) and are loaded into variables in captured or manually coded scripts. In this
framework, variables are used for both input values and output verification values.
Navigation through the program, reading of the data files, and logging of test status and
information are all coded in the test script
Modularity-driven testing
The test script modularity framework requires the creation of small, independent scripts
that represent modules, sections, and functions of the application-under-test. These small
scripts are then used in a hierarchical fashion to construct larger tests, realizing a
particular test case.
'####################################################
'# Descriptive Programming Objects
'####################################################
'# Modifications: Enter changes to the code in this space
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 17
'####################################################
'# Public Sub WebTableLink (strWebLink)
'####################################################
'# Modifications: Enter changes to the code in this space
'####################################################
Public Sub DPWebEdit (strWebEdit,strInValue)
If strInValue <> "" Then
Set obj_WebEdit = Description.Create
obj_WebEdit ("Class Name").value = "WebEdit"
obj_WebEdit ("name").value= strWebEdit
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebEdit(obj_WebEdit).Set
strInValue
End If
End Sub
'########################################################
Public Sub DPWebEditSetSecure (strWebEdit,strInValue)
If strInValue <> "" Then
Set obj_WebEdit = Description.Create
obj_WebEdit ("Class Name").value = "WebEdit"
obj_WebEdit ("name").value= strWebEdit
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebEdit(obj_WebEdit).SetSecure
strInValue
End If
End Sub
'########################################################
Public Sub DPWebList (strWebList,strInValue)
If strInValue <> "" Then
Set obj_WebList = Description.Create
obj_WebList ("Class Name").value = "WebList"
obj_WebList ("name").value= strWebList
Reporter.Filter = 3 'Turn Reporting of
Call TestListValues (obj_WebList,strInValue) 'Check for valid item in list
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 18
Reporter.Filter = 0 'Turn Reporting on
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebList(obj_WebList).Select
strInValue
End If
End Sub
'########################################################
Public Sub DPRadioGroup (strWebRadioGroup,strInValue)
Set obj_WebRadioGroup = Description.Create
obj_WebRadioGroup ("Class Name").value = "WebRadioGroup"
obj_WebRadioGroup ("name").value= strWebRadioGroup
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebRadioGroup(obj_WebRadioGroup).Sele
ct strInValue
End Sub
'####################################################
Public Sub DPWebImage (strImage)
Set obj_Image = Description.Create
obj_Image ("Class Name").value = "Image"
obj_Image ("name").value= strImage
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).Image(obj_Image).Click '6,7
End Sub
'####################################################
Public Sub DPWebCheckBox (strWebCheckBox,strInValue)
Set obj_WebRadioGroup = Description.Create
obj_WebCheckBox ("Class Name").value = "WebCheckBox"
obj_WebCheckBox ("name").value= strWebRadioGroup
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebCheckBox(obj_WebCheckBox).Select
strInValue
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 19
End Sub
'####################################################
Public Sub DPWebLink (strWebLink)
Set obj_WebLink = Description.Create
obj_WebLink ("Class Name").value = "Link"
obj_WebLink ("name").value= strWebLink
Count = 1
Do until Browser(strBrowser).Page(strPage).Link(obj_WebLink).Exist
if Browser(strBrowser).Page(strPage).Link(obj_WebLink).Exist Then
Exit Do
End If
Count = Count + 1
If Count = 20 Then
Exit Do
end if
Loop
Browser(strBrowser).Page(strPage).Link(obj_WebLink).Click
End Sub
'####################################################
Public Sub DPWebButton (strWebButton)
Set obj_WebButton = Description.Create
obj_WebButton ("Class Name").value = "WebButton"
obj_WebButton ("name").value= strWebButton
Browser(strBrowser).page(strPage).Sync
Browser(strBrowser).Page(strPage).WebButton(obj_WebButton).Click
End Sub
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 20
'####################################################
' Close all opened browsers
‗####################################################
Public Function CloseBrowsers
If Browser("micclass:=Browser").Exist (0) Then
Browser("micclass:=Browser").Close
End If
While Browser("micclass:=Browser", "index:=1").Exist (0)
Browser("index:=1").Close
Wend
If Browser("micclass:=Browser").Exist (0) Then
Browser("micclass:=Browser").Close
End If
End Function
‗#####################################################
Set myBrowser = Description.Create
myBrowser("version").value = "internet explorer 7"
Set eachBrowser = Desktop.ChildObjects(myBrowser)
b= eachBrowser.count()
msgbox "No of Windows Browsers Opened" & VBNewLine &b
For i = 1 to b - 1
msgbox "Browser Names" &eachBrowser(i).getroproperty("text")
eachBrowser(i).close
Next
‗####################################################
‗ Launch Application
' returns - always returns true
‗####################################################
Public Function Launch (apptype, val)
If "website" = apptype Then
thirdlevel = ""
Report micPass, "Initialize", "Initializing Framework"
level = split(webLevels, leveldelimiter, -1, 1)
desc = split(webLevelsDesc, leveldescdelimiter, -1, 1)
object = split(objects, objectdelimiter, -1, 1)
objectDescription = split(objectsDescription, objectsDescriptiondelimiter, -1, 1)
CloseBrowsers
Set IE = CreateObject("InternetExplorer.Application")
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 21
IE.visible = true
IE.Navigate val
While IE.Busy
wait 1
Wend
End If
initialized = true
Launch = true
End Function
‗####################################################
‗ WebElement Items
‗####################################################
Set oDesc = Description.Create()
oDesc("Class Name").Value = "WebElement"
oDesc("Class").Value = "hp_hclist_box"
rc = Browser("WebMD - Better information.").Page("WebMD - Better
information.").WebElement(oDesc).GetROProperty("innertext")
sp = Split(rc, " ")
Msgbox sp(4)
‗####################################################
Set Desc= description.Create()
desc("micclass").value ="WebCheckBox"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
‗####################################################
Set Desc= description.Create()
desc("micclass").value ="WebEdit"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 22
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
‗####################################################
Set Desc= description.Create()
desc("micclass").value ="WebRadioButton"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
‗####################################################
Set Desc= description.Create()
desc("micclass").value ="WebButton"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
‗####################################################
‗ Links and URL‘s
‗####################################################
Set oDesc = Description.Create()
oDesc("html tag").Value = "A"
Set rc = Browser("Google").Page("Google").ChildObjects(oDesc)
num = rc.Count()
For i=0 to num-1
tag = rc(i).GetROProperty("innertext")
href = rc(i).GetROProperty("href")
Reporter.ReportEvent 0, "Links in Page", "name: " & tag &"; url:" & href
Next
‗####################################################
‗ Automation Object Model
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 23
‗####################################################
Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Test.Settings.Launchers("Web").Active = False
App.Test.Settings.Launchers("Web").Browser = "IE"
App.Test.Settings.Launchers("Web").Address = "http://newtours.mercury.com "
App.Test.Settings.Launchers("Web").CloseOnExit = True
App.Test.Settings.Launchers("Windows Applications").Active = False
App.Test.Settings.Launchers("Windows Applications").Applications.RemoveAll
App.Test.Settings.Launchers("Windows Applications").RecordOnQTDescendants = True
App.Test.Settings.Launchers("Windows Applications").RecordOnExplorerDescendants =
True
App.Test.Settings.Launchers("Windows Applications").RecordOnSpecifiedApplications
= True
App.Test.Settings.Run.ObjectSyncTimeOut = 20000
App.Test.Settings.Run.DisableSmartIdentification = False
App.Test.Settings.Run.OnError = "Dialog"
App.Test.Settings.Resources.Libraries.RemoveAll
App.Test.Settings.Resources.Libraries.Add("E:\childobject3.vbs")
App.Test.Settings.Resources.Libraries.Add("E:\WriteToexcel.vbs")
App.Test.Settings.Resources.Libraries.Add("E:\SugarCRM.vbs")
App.Test.Settings.Web.BrowserNavigationTimeout = 60000
App.Test.Settings.Web.ActiveScreenAccess.UserName = ""
App.Test.Settings.Web.ActiveScreenAccess.Password = ""
App.Test.Settings.Recovery.Enabled = True
App.Test.Settings.Recovery.SetActivationMode "OnError"
App.Test.Settings.Recovery.Add "E:\aaaa.qrs", "Recov_Popup", 1
App.Test.Settings.Recovery.Item(1).Enabled = True
App.Test.Environment.LoadFromFile("E:\InputDataSheet.ini")
' **************************************************
Function Library
‗********************************
' Registering both functions
RegisterUserFunc "WebTable", "ObjectsByMicClass", "ObjectsByMicClass"
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 24
RegisterUserFunc "WebTable", "ItemByKeyColumn", "ItemByKeyColumn"
' Function: ObjectsByMicClass
' Description: Returns a collection of objects all the objects in a
' WebTable that have the specified MicClass
' Return Value: A Collection of Objects
' Arguments:
' Obj - Test Object (WebTable)
' micClass - The micClass of the objects to retrieve
'##################################################
Function ObjectsByMicClass(Obj, micClass)
Set Table = Obj
' Create a collection object to hold the items
Set objCollection = CreateObject("Scripting.Dictionary")
' Go over all the cells in the table, and look for objects with the specified micClass
For row=1 to Table.RowCount
ColumnCount=Table.ColumnCount(row)
For col=1 to ColumnCount
For ItemIndex=0 to Table.ChildItemCount(row, col, micClass)-1
Set childItem=Nothing
Set childItem = Table.ChildItem(row, col, micClass, ItemIndex)
If Not childItem is Nothing Then
' If the cell contains a micClass object, add it to the collection
ItemKey = objCollection.Count + 1
objCollection.Add ItemKey, childItem
End if
Next
Next
Next
Set ObjectsbyMicClass = objCollection
End Function
‗#######################################################
' Function: ItemByKeyColumn
' Description: Returns an item from a column, based on the value of a
' key column
' Return Value: Object
' Arguments:
' Obj - Test Object (WebTable)
' KeyColumnIndex - Index of the KeyColumn
' KeyColumnValue - Value to search for in the key column
' KeyItemIndex - Index of the value in the key column (if there is
' more than one). If 0, the first item will be used.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 25
' TargetColumnIndex - Column from which to retrieve the target item
' micClass - The micClass of the target item
' TargetItemIndex - Index of the target item to retrieve (if there is
' more than one). If 0, the first item will be used.
‗#######################################################
Function ItemByKeyColumn(Obj, KeyColumnIndex, KeyColumnValue, KeyItemIndex,
TargetColumnIndex, micClass, TargetItemIndex)
Table = Obj
rowCount = Table.RowCount
' if TargetItemIndex was not specified, use 1 as deafult
If TargetItemIndex < 1 Then
TargetItemIndex = 1
End If
' if KeyColumnIndex was not specified, use 1 as default
If KeyItemIndex < 1 Then
KeyItemIndex = 1
End If
' look for KeyColumnValue in the key column to determine which
' row to retrieve the targe item from
Row = 0
foundIndex = 0
While Row <= RowCount And foundIndex < KeyItemIndex
Row = Row + 1
CellData = Table.GetCellData(Row, KeyColumnIndex)
If CellData = KeyColumnValue Then
foundIndex = foundIndex + 1
End If
Wend
If foundIndex < KeyItemIndex Then
Exit Function
End If
' Now that we know the row, retrieve the item (according to its micClass)
' from the target column.
ChildItemsCount = Table.ChildItemCount(Row, TargetColumnIndex, micClass)
If ChildItemsCount > =1 And ChildItemsCount >= TargetItemIndex Then
Set GetItemByKeyColumn = Table.ChildItem(Row, TargetColumnIndex,
micClass, TargetItemIndex-1)
End If
End Function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 26
' ************************************
' Using the ItemByKeyColumn Function
‗##################################################
Set obj = Browser("Table with objects").Page("Itenerary: Mercury
Tours").WebTable("Acapulco to
Zurich").ItemByKeyColumn(1,"FLIGHT",2,3,"WebElement",1)
msgbox obj.GetROProperty("innerhtml")
' Using the ObjectsByMicClass function
Set collection =
Browser("Browser").Page("Page").WebTable("Table").ObjectsByMicClass("WebCheck
Box")
For i=1 to collection.count
If collection(i).GetROProperty("checked") Then
collection(i).Set "OFF"
Else
collection(i).Set "ON"
End If
Next
‗##########################################
' Example 1
‗#############################################
Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 27
‗##################################################
' Example 2
‗###############################################
Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
ObjMail.Send
Set objMail = Nothing
End Function
‗############################
‗ InString
‗############################
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP" ' String to search in.
SearchChar = "P" ' Search for "P".
MyPos = Instr(4, SearchString, SearchChar,1) ' A textual comparison starting at position
4. Returns 6.
msgbox mypos
MyPos = Instr(1, SearchString, SearchChar, 0) ' A binary comparison starting at
position 1. Returns 9.
msgbox mypos
MyPos = Instr(SearchString, SearchChar) ' Comparison is binary by default (last
argument is omitted). Returns 9.
msgbox mypos
MyPos = Instr(1, SearchString, "W") ' A binary comparison starting at position 1.
Returns 0 ("W" is not found).
msgbox mypos
‗########################################
QTP 10.0 Features
1. QC integration – Which (mostly) down to Resource Management and Source
Resource Management: Although you could keep saving your resources as attachments
(for backward compatibility), you can upgrade to a new, fuller mode of work. This
includes a whole new Resource module in QC, and allows for some very neat tricks on
Function Libraries, Tests and Object Repositories etc.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 28
It should be noted, though, that other types of files (external excel / XML files, for
example), remain as unmanaged attachments.
Resources have full meta-data, and have a special view pane – you can view Object-
Repositories, data-tables, and function libraries code right from QC. This looks quite
nice; however, I missed the ability to open the resource for editing in QTP with a single
click.
Automatically updated path system – When moving a function library between folders,
QC will automatically update all the tests which depend on it, so they will use it at its
new location. This makes the once critical problem of hard-path-link a non-issue. Very
impressive.
A word about the user interface – when opening a QC resource / test from QTP, the file
dialog shows the items with large, crisp icons, very similar to Word‘s save dialog.
Everything is very clear and intuitive, as is the ability to revert back to saving / opening a
test from the File-System.
What about your existing projects? Well, when upgrading to QC 10, a wizard will
automatically transform all you unmanaged attachments to managed resources (if you‘d
like it to).
Source Control: This includes a very rich line of features which are very well executed,
and effectively allow you to manage a QTP project as any other code project:
First, the basics – QTP and QC 10 introduce a new Check-in/Check-out ability. It
works similar to what you‘d expect – a checked out item will be locked to all other users,
and you can immediately know an item‘s status by looking at its icon (green/red locks).
An interesting twist regards manner in which a test / resource is locked – it‘s at the user
level (not the local machine level). This means that if you log into QC from a different
machine, you‘ll have access to all your checked-out items, even if they were originally
checked-out on a different local machine. The ability is implemented very well, both
from QTP‘s end, as well as from QC‘s end.
A major enabler for source control is the new versioning feature of QC. It manifests
both with a kind of instant versioning for a single resource, and with a project-wide
―base-line version‖, which allows you to revert your entire test framework to a previous
version. Both types of versioning are supported by a surprisingly robust comparison
mechanism. You can select two versions of a resource / test, a see a very detailed
comparison of their respective changes. For function libraries this amounts to a ―simple‖
text comparison, but this feature truly shines in full test comparisons.
It will present changes in the different actions and their resources (data-table, object
repositories, inner code), as well as in the global test-settings, associated function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 29
libraries, recovery scenarios, and pretty much anything you could think of. The ability to
drill-down into the data is very impressive; and the effective, concise manner in which
the data is presented in the top level view is downright unbelievable. A nice touch is a
small screen capture of the change, in case you don‘t remember what ―Run all rows –
>Changed into-> Run a single iteration only‖ means (for example).
Now to the versioning mechanism itself: Whenever you check and item in, a new
―version‖ will be created, and you‘ll be able to revert back to it with ease. As this is a
version of a single, isolated resource, I found it better to refer to it as a SnapShot – my
terminology, not HP‘s. The snapshots are visible both from QC and QTP, and you can
very easily choose which one to open. This allows you a kind of an instant undo to a
single file which worked in the past, but is broken in the present.
The second mechanism presents the ability to select several folders, and create a full
blown ―base-line version‖ of them and everything they relate to. Defects, inner-
connections, tests, history data, resources – all these and more will be ―frozen‖ and
preserved as a base-line. You can then choose to revert back to an old baseline, and truly
regain all the abilities that were present at that time. As all the resources, attachments
tests and reports will be restored, you don‘t have to worry about forgetting anything, or
leaving some minor resource at the wrong version. This is versioning with a vengeance –
it allows you to track the AUT‘s versions with your own automation versions, enabling,
among other things, running automation efforts on several AUT versions at once.
For conclusion – The new abilities inherit in the connection of QTP and QC Atlantis are
(or at least seem to be) revolutionary. At last, QTP projects can be natively managed as
code projects; and some of the supporting infrastructure is surprisingly robust and useful.
As a ―raving‖ anti-QC-ist, I must admit QC Atlantis seem tempting, and for me, that‘s
saying a lot!
I must contrast these very positive impressions with some dire problems: The versioning
feature will put a stain on your storage capabilities (though less than creating a simple
copy the data); all these wonderful features are available only if both your QTP and QC
are upgraded to Atlantis; and a critical issue – Previous versions of QTP will not work
with QC Atlantis. Yes, this is not a misunderstanding, there is no backward
compatibility between QC to QTP (although QTP Atlantis will work with any version of
QC). On top of these, performance may become an issue, though we were unable to
precisely evaluate it, as our QC was installed on an already overtaxed personal computer.
2. Report improvements
The native QTP report includes several new improvements:
Tracability: Selecting a report-node will automatically focus on the relevant code-line in
the script. This may sound like a cool feature at first, but a closer look revels that it only
works for actions (not functions); and that in any case, using a custom report function (as
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 30
most of us do) completely nullifies the feature (since you‘re always at the same code line
when performing the report).
Exporting: The report now has a two-click export feature, which comes with a built-in
ability to export to Word and PDF documents, as well as the ability to export through a
custom XSL of your choosing. You can choose between Short and Long formats
(corresponding to PShort.XSL and PDetails.XSL) to get a document relevant to your
needs. This blessed feature has one major flaw – It has no API support. This means that
you cannot export the results automatically at the end of a test run, which is quite a miss,
to say the least.
Resource Monitor: QTP can now hook onto the Windows Performance Monitor and
present it as part of the test results. You can select several counters to monitor (e.g. GDI
objects, memory usage etc.), and the monitor output graph will be available in special tab
in the result window. You can set up a ―checkpoint‖ for a counter (e.g. Fail the test if
there are more than 500 GDI objects), facilitating a kind of a poor-man‘s version of load-
testing.
The fact that clicking the graph focuses on the relevant test step (as well as the other way
around), provides an effective way to quickly locate problematic actions and resource
usage spikes. This feature is well executed, and HP has even went the extra mile and
added several unified counters that simplify monitoring the application. However, the
fact that you can only monitor one process per test may leave the more advanced users
with their own implementation of a resource monitor.
Considering the simple design and implementation of this feature, I believe it will
become a popular tool in every automation project that uses QTP 10.
Native image integration: This is a small, yet long-awaited feature. The ReportEvent
command now has a new optional parameter – you can specify a path to a picture file,
and it will be attached to the report node of the current event. When used in conjunction
with the CaptureBitmap method, this presents a technical, yet revolutionary upgrade to
the native QTP report. Finally, users can attach screenshots to their custom report events
without any special functions or frameworks.
3. IDE improvements
Intellisense: Perhaps I‘m doing injustice to the other features, but the IDE improvements,
and the new intellisense engine in particular, is what got me excited about QTP Atlantis.
So I was pretty much on the edge of my seat when we‘ve gotten to this last part of the
presentation. I‘m very pleased to say that it was every bit what I imagined it to be, with
the exception of intellisense for VBScript classes, and intellisense in the debug viewer
(both won‘t be implemented). Luckily, there are workarounds for both these issues
through the PDM hack (for debug intellisense), and WSC registration (for VBScript
Class intellisense through COM).
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 31
We saw a demonstration of how creating an Excel COM object provided a full
intellisense for all its methods and properties, for as many levels as we‘d like. Every
variable set to this object also presented the same intellisense, and the autocomplete
caught every variable we‘ve defined or used (yes, there‘s autocomplete for variable
names!). The autocomplete and intellisense features worked smoothly, and presented no
apparent performance issue. It‘s still left to be seen how it functions in a real script,
with hundreds / thousands code lines.
Tasks and Comment Pane: QTP has a new bottom pane which includes a run-of-the-
mill implementation of tasks and comments. Double clicking a comment will take you to
the relevant code-line, though strangely enough, you cannot do this with a task (i.e.,
tasks cannot be linked to specific code lines). It was mentioned that enabling the
comments feature for function libraries may sometimes cause performance issues.
Dynamic code-zones: When standing inside a code block like If, While, Do, etc, the IDE
will mark the relevant block with blue lines, making it much more easy to make your way
inside nested blocks of this sort (somewhat like highlighting left-right bracket pairs).
While it will surely make our life easier, a more robust mechanism like collapsible code-
regions is still needed.
Custom Toolbars: You can add your own buttons and commands to QTP toolbars and
menus. While this does not include inner-QTP macros, you can assign a program / File
shortcut to your own button / menu item. It‘s nice, but i think it will only gain power once
QTP‘s inner mechanisms will be bindable to such buttons.
4. Miscellaneous features
General look and feel: QTP has departed from the old Tab layout, and into the more
modern settings-tree layout (similar to Office, EMule, Adobe, and pretty much every
other program). It‘s nice, but nothing as groundbreaking as the transformation in QTP
9.0.
Bitmap Checkpoint improvements: These include presenting the size of the selected
area when choosing to check only a part of an Image, as well as the ability to plug your
own custom DLL for comparing images. I suppose that there are some projects for which
this can actually be quite revolutionary. Another great addition is the ability to see the
difference between the expected and actual bitmaps in a separate tab.
API changes: QTP Automation API will receive several upgrades, the most noteworthy
of which is the ability to read and write that code of the test you‘ve opened. Writing the
code will not effect an ongoing run-session (there goes my ambitious try-catch
implementation for QTP), but it still opens the door for some creative tweaks and
hacks…
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 32
Saving a test with all linked resources: For those who‘re working with QC, this is a real
blessing. Up until QTP 10, copying a QC saved test to your local system was a hellish
procedure of changing each and every resource and action reference to your local file-
system. QTP and QC Atlantis offer a one-click solution for copying a test and all its
resources to your local file-system, and automatically changing all the references
accordingly.
Dynamic Action Call: I‘ve saved the best for last. QTP 10 presents a new native
command – LoadAndRunAction. It allows you to load external actions during the run-
session, without having to associate them with your test beforehand. All the run-time
debug abilities will be available for these dynamically added actions, so you‘re not giving
anything up by using this feature. I think it‘s a long awaited feature, and a well executed
one.
What surprises are in store in QTP?
1. Stronger than ever Quality Center integration.
An external resources manager: No more hellish workarounds for saving resources as
attachments (function libraries, shared OR etc.). From now on, an external resource will
become a fully-fledged QC entity, with its own meta-data (which means it‘s searchable!),
fields and versions.
Versions: QTP tests and all the external resources will now have full versioning support.
This will include reverting back to an old version (immediately, from the open file menu
if you‘d wish), as well as comparing versions - from the attached resources of the tests,
though the objects in the SOR, to the changed lines in the function library files.
Versioning is available for manual tests as well, thus allowing for a very smooth
integration of automation with manual testing.
I must say that this is one feature I would consider migrating my tests to Quality Center
for.
2. Intellisense
It’s a known fact that the QTP intellisense popup can be quite annoying – just when
you‘re dealing with a very complex .Net/Java object, the window proves to be too narrow
to fully display the object‘s properties and methods. Tarun has continued his great work
on providing productivity enhancing tools and code libraries, and has posted a resizer for
the intellisense popup window.
COM objects intellisense - for example, if you‘d use an Excel.Application object, you‘d
see all its inner methods and properties, up to the N-th level
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 33
Variable bridge intellisense - which means that if you‘d assign some object to a
variable, the variable will have the same intellisense as the original object
These three abilities present the bulk of abilities you would like to have in an intellisense
system. It‘s not that there isn‘t room for more abilities, but these three are sure to make
working with the new QTP an entirely different experience. It‘s unclear if this would
include auto-complete for script variables, but my guess is that it will.
I was told that all these intellisense features will not apply to VBScript classes, but only
to COM objects and RO objects. As one who relays heavily on my own VBScript classes,
I was very disappointed. However, it must be said that not a lot of QTP programmers
work with their own VBScript classes, so it‘s a shortcoming that only a handful of people
should mind.
3. More IDE improvements
These include the integration of a comment driven To-Do pane, as well as a jump-to-
comment ability. Not anything out of the ordinary, but a blessed addition to the very
limited QTP IDE environment. Further more, and three versions too late – Toolbar
customizations! You could rearrange existing icons, as well as add calls to external
commands (e.g. launch the AUT) as separate icons.
4. Reporter improvements
The reporter will now be able to natively export the HTML to PDF (and perhaps some
other formats).
A completely new feature will be an integrated performance counter which would
monitor the computer resources throughout the test. This, combined with a new ability to
jump to the relevant script live from the report will facilitate a whole new level of testing
– almost like a poor-man‘s version of a load test.
However, there‘s still no word on filtering, searching, and running several reporters
concurrently (although the infrastructure exists since QTP 8.2). Another overlooked issue
is the report‘s availability in case of a mid-run crash.
5. New checkpoint abilities
You could set up a whole new kind of checkpoint for the computed resources – for
example, fail the test if the application uses more than 500 GDI objects, and other
parameters. This ability is closely coupled with the new resource monitor report. Another
welcomed improvement is the ability to hook up your own algorithm for image
comparison straight into QTP‘s native image checkpoint mechanism.
6. New environments
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 34
It will include at least: Windows XP SP3, Windows 2008, Windows Vista SP1, IE8,
FireFox 3, the new cirtrix client.
PRODUCT ENHANCEMENTS
Upgrade from QuickTest 9.5 - If you have QTP 9.5 Installed on the system, you can
choose to upgrade to version 10.0. This will allow you to preserve some of the
configuration settings and options that you already have set up.
Improved IntelliSense Functionality - QTP now provides full IntelliSense for objects
created by a step or function (i.e. objects created by Create Object method), variables to
which an object is assigned, reserved objects, COM objects and properties that return
objects. In addition, Intellisense sentence completion now provides lists of local
variables.
Added Control for Editing and Managing Actions in Automation Scripts - The QTP
Automation Object Model has a new set of objects and methods for manipulating test
actions and action parameters. You can use automation scripts to create new actions,
modify and validate the syntax of action scripts, create and modify action parameters, and
more.
Improved Debugger Pane Design and Functionality - The Debug Viewer pan has a
new look, including icons to help you identify the type of information displayed.
New Object Identification Solutions in Maintenance Run Mode - In addition to
helping you update your steps and object repositories when objects in application change,
the Maintenance Run Wizard can now help you solve problems dealing with test failures
due to missing objects, or objects that can only be recognized via Smart Identification.
Additional Configuration Settings for Text Recognition Mechanism - You can now
set all text recognition configuration settings from the QuickTest Options Dialog Box
New Look for Options, Settings, and File Dialog Boxes - The QuickTest Options and
Settings dialog boxes have changed from their former ta-based design to a more easily
navigable tree-based structure. The tree contains only the options relevant for the add-ins
that are currently loaded.
QuickTest Toolbar Customization Options - You can use the new Customize Dialog
box to customize the appearance of existing menus and toolbars, and to create your own
user-defined menus, toolbar buttons, and shortcuts.
Improved Web Extensibility - QTP Web Add-in Extensibility enables you to develop
packages that provide high level support for thir-party and custom Web controls that are
not supported out-of-the-box by the Web Add-in.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 35
NET Add-in and Extensibility Improvements - The .NET Add-in has several new
objects and methods, including the SwfPropertyGrid test object (for working with .NET
Windows Forms property grids), GetErrorProviderText method and ErrorProviderText
identification property.
New Terminal Emulator Configuration Validation - The new Terminal Emulator pane
of the Options dialog box now includes a Validate button. When you click this button,
QTP checks the current configurations of the selected emulator. If a problem is detected,
a brief description is displayed in the pane.
NEW SUPPORTED OPERATING SYSTEMS AND ENVIRONMENTS
Microsoft Windows 2008 Server 32-bit Edition
Microsoft Windows 2008 Server 64-bit Edition
Microsoft Windows Vista, Service Pack 1, 32-bit Edition
Microsoft Windows Vista, Service Pack 1, 64-bit Edition
Microsoft Windows XP Professional 32-bit Edition -- Service Pack 3
Citrix Presentation Server 4.5
Microsoft Internet Explorer 8, Beta 2
Mozilla firefox 3.0.x
Delphi: IDE, versions 6, 7, and 2007 (for controls based on the Win32 VCL
library)
SAP: CRM 2007 (For controls that support test mode enhancements
Java: IBM 32-bit JDK 1.5.x, SWT toolkit version 3.4
Java Extensibility: Eclipse IDE 3.4
NET: .NET Framework 3.5 -- Service Pack 1
// ** TO Count Broken Links in Web Page Using VBScript
1.
Set obj=Browser(―name:=Blackboard.*‖).Page(―title:=Blackboard.*‖).
Frame(―name:=main.*‖).object.all.tags(―IMG‖)
Msgbox obj.length
For each element in obj
s1=element.nameProp
If Browser().Page().Frame().Image(―filename:=―&s1,‖index:=0‖).exist(0) then
If Browser().Page().Frame().Image(―filename:=―&s1,‖index:=0‖).
Object.complete=―True‖ then
Msgbox ―pass‖
Else
Msgbox ―fail‖
End if
End if
Next
// TO Count Broken Links in Web Page Using VBScript
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 36
If Browser(―my_web‖).Page(―GlobalPage‖).Link(―Logout‖).
GetROProperty(―href‖)<>―javascript:__doPostBack('ctl00$lkLogout','Logout')‖ Then
Reporter.ReportEvent micFail ,‖href‖,Browser(―my_web‖).
Page(―GlobalPage‖).Link(―Logout‖).GetROProperty(―href‖)
End If
// // TO Count Broken Links in Web Page Using VBScript
Verify Broken Links using VBscript (without checkpoints)
One of my friends just wanted to check for the broken links (both textlinks and image
links) on the page with VB script and not the checkpoints.
Set obj=Browser("name:=Blackboard.*").Page("title:=Blackboard.*").
Frame("name:=main.*").object.all.tags("IMG")
Msgbox obj.length
For each element in obj
s1=element.nameProp
If Browser().Page().Frame().Image("filename:="&s1,"index:=0").exist(0) then
If
Browser().Page().Frame().Image("filename:="&s1,"index:=0").Object.complete="True"
then
Msgbox "pass"
Else
Msgbox "fail"
End if
End if
Next
// TO Count Broken Links in Web Page
Broken Links also sometimes called as dead links are those links on the web which are
permanently unavailable. Commonly found, 404 error is one example of such link. Now
the question is how can we identify broken links with the help of QTP during the run
session?
There can be two ways to do this:
1. Using Automatic Page checkpoint.
2. By manually creating a Page checkpoint.
Using Automatic Page checkpoint: Go to Tools > Options > Web > Advanced and
check the two boxes labeled ―Create a checkpoint for each page while recording‖ and
―Broken Links‖
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 37
Now every time you record a new page, QTP will automatically include a checkpoint for
broken links.
By manually creating a Page checkpoint: QTP does not provide a direct menu option
to incorporate a page checkpoint. You need to take the help of standard checkpoint. Start
recording session > Insert > Checkpoint > Standard Checkpoint (OR press F12). Place
and click the hand pointer anywhere on your web page. Select Page (As shown in picture
below) and Click OK.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 38
You will get the following screen:
Check ―Broken Link‖ checkbox down below and click OK.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 39
Now, how will you verify page checkpoint and hence broken links?
Run the above script. Go To Test Results > Your Check Point. Check the status of all
links under ―Broken Links Result‖
If you want to verify links pointing only to the current host check the box titled “Broken
Links- check only links to current host” under Tools > Options > Web. Similarly if
you want to verify links pointing to other hosts as well, uncheck it.
// TO Count No of Links in Web Page
How to return the total number of links in a webpage and their names and URLs
Solution: Use ChildObjects to get the link collection, then retrieve the properties
Use the ChildObjects method to retrieve all the links on the specified webpage.
Once you have the collection, you can use the GetROProperty method to retrieve the
innertext (name) and href (URL) values.
object.ChildObjects (pDescription)
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 40
Example: ‗ The sample was created against www.google.com
Set oDesc = Description.Create()
oDesc(―html tag‖).Value = ―A‖
Set rc = Browser(―Google‖).Page(―Google‖).ChildObjects(oDesc)
num = rc.Count()
For i=0 to num-1
tag = rc(i).GetROProperty(―innertext‖)
href = rc(i).GetROProperty(―href‖)
Reporter.ReportEvent 0, ―Links in Page‖, ―name: ― & tag & ―; url: ― & href
Next
// TO Count No of Links in Web Page
Simple Code To Check All Links
Set oDesc = Description.Create()
oDesc(―html tag‖).Value = ―A‖
Set rc = Browser(―title:=.*‖).Page(―title:=.*‖).ChildObjects(oDesc)
num = rc.Count()
For i=0 to num-1
Set rc = Browser(―title:=.*‖).Page(―title:=.*‖).ChildObjects(oDesc)
ref = rc(i).GetROProperty(―href‖)
Browser(―title:=.*‖).Page(―title:=.*‖).link(―text:=.*‖,‖index:=―&i).click
Browser(―title:=.*‖).sync
title1=Browser(―title:=.*‖).getRoproperty(―title‖)
MsgBox title1
Browser(―title:=.*‖).navigate(ref)
‘Navigates to the url taken from ―href‖ property
Browser(―title:=.*‖).sync
title2=Browser(―title:=.*‖).getRoproperty(―title‖)
‘get the tile of the tNavigated page
MsgBox title2
If title1=title2 Then
‘condition to check for the targetted page and Navigated page
Reporter.ReportEvent 0, ―Navigated To Correct Page‖,‖―&title1
′Reports if correct
else
Reporter.ReportEvent 1,‖―&title1,‖―&title2
End If
Browser(―title:=.*‖).back
‘Navigates back to main page
Browser(―title:=.*‖).sync
Next
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 41
// Chaild Objects
Set desc = Description.Create()
Set col = Browser(―name:=Google‖).Page(―title:=Google‖).ChildObjects(desc)
ct = col.Count()
msgbox ct
Set desc2 = Description.Create()
desc2(―micclass‖).Value = ―WebElement‖
Set col2 = Browser(―name:=Google‖).Page(―title:=Google‖).ChildObjects(desc)
ct2 = col.Count()
msgbox ct2
Set desc3 = Description.Create()
desc3(―html tag‖).Value = ―INPUT‖
Set col3 = Browser(―name:=Google‖).Page(―title:=Google‖).ChildObjects(desc)
ct3 = col.Count()
msgbox ct3
// Get Each Radio in RadioGroup And Check
Set opt=Description.Create
opt(―html tag‖).value=―INPUT‖
opt(―type‖).value = ―radio‖
Dim allOptions,all
Set allOptions=Browser(―a‖).Page(―b‖).Frame(―c‖).ChildObjects(opt)
all=allOptions.count
MsgBox all for i= 0 to all
eName=allOptions(i).getROProperty(―name‖)
noofradio=allOptions(i).getElementsByName(eName).length
for j= 0 to noofradio-1
radioname=allOptions(i).object.document.getElementsByName(eName).item(j).GetAdju
centText(―afterend‖)allOptions(i).object.document.getElementsByName(eName).item(j).
checked=true
msgbox radioname
next
next
// Copy an excel sheet to another excel
Following is the code to copy the conntents of a sheet in one excel to another excel sheet
Set objExcel = CreateObject(―Excel.Application‖)
objExcel.Visible = True
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 42
Set objWorkbook1= objExcel.Workbooks.Open(―C:\Documents and
Settings\mohan.kakarla\Desktop\1.xls‖)
Set objWorkbook2= objExcel.Workbooks.Open(―C:\Documents and
Settings\mohan.kakarla\Desktop\2.xls‖)
objWorkbook1.Worksheets(―Sheet1″).UsedRange.Copy
objWorkbook2.Worksheets(―Sheet1″).Range(―A1″).PasteSpecial Paste =xlValues
objWorkbook1.save
objWorkbook2.save
objWorkbook1.close
objWorkbook2.close
set objExcel=nothing
//Compare 2 Excel sheets cell by cell
This code will open two excel sheet and compare each sheet cell by cell, if any changes
there in cells , it will highlight the cells in red color in the first sheet.
Set objExcel = CreateObject(―Excel.Application‖)
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open(―C:Documents
andSettingsmohan.kakarlaDesktopDocs1.xls‖)
Set objWorkbook2= objExcel.Workbooks.Open(―C:Documents and
Settingsmohan.kakarlaDesktopDocs2.xls‖)
Set objWorksheet1= objWorkbook1.Worksheets(1)
Set objWorksheet2= objWorkbook2.Worksheets(1)
For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 3′Highlights in red color if any changes in cells
Else
cell.Interior.ColorIndex = 0
End If
Next
set objExcel=nothing
// Excel Sorting By Row:
Const xlAscending = 1
Const xlNo = 2
Const xlSortRows = 2
Set objExcel = CreateObject(―Excel.Application‖)
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open(―C:Documents and
Settingsmohan.kakarlaDesktopDocs1.xls‖)
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1,1).activate
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 43
Set objRange = objExcel.ActiveCell.EntireRow
objRange.Sort objRange, xlAscending, , , , , , xlNo, , , xlSortRows
set objExcel=nothing
Excel Sorting By Colum :
Const xlAscending = 1
′represents the sorting type 1 for Ascending 2 for Desc
Const xlYes = 1
Set objExcel = CreateObject(―Excel.Application‖)
‘Create the excel object
objExcel.Visible = True
‘Make excel visible
Set objWorkbook = _
objExcel.Workbooks.Open(―C:\Documents and
Settings\mohan.kakarla\Desktop\Docs1.xls‖)
‘Open the document
Set objWorksheet = objWorkbook.Worksheets(1)
‘select the sheet based on the index .. 1,2 ,3 …
Set objRange = objWorksheet.UsedRange
‘which select the range of the cells has some data other than blank
Set objRange2 = objExcel.Range(―A1″)
‘ select the column to sort
objRange.Sort objRange2, xlAscending, , , , , , xlYes
set objExcel=nothing
// DELETE ROWS FROM XL SHEET
Public Function BIP_xlsDeleteRowRange (sSrcPath, sDestPath, sStartRow, sEndRow)
‗Create Excel object
Set oExcel = CreateObject(―Excel.Application‖)
‗Sets the application to raise no app alerts
‗In this case it will allow a file overwrite w/o raising a ‗yes/no‘ dialog
oExcel.DisplayAlerts = False
‗Open Book in Excel
Set oBook = oExcel.Workbooks.Open(sSrcPath)
‗Set Activesheet
Set oSheet = oExcel.Activesheet
‗Delete row range
oSheet.Rows(sStartRow +‖:‖+ sEndRow).Delete
‗Save new book to Excel file
oBook.SaveAs (sDestPath)
‗Close the xls file
oExcel.Workbooks.Close()
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 44
End Function
// DELETE COLUMNS FROM XL SHEET
Public Function BIP_xlsDeleteColumnRange (sSrcPath, sDestPath, sStartCol, sEndCol)
‗Create Excel object
Set oExcel = CreateObject(―Excel.Application‖)
‗Sets the application to raise no app alerts
‗In this case it will allow a file overwrite w/o raising a ‗yes/no‘ dialog
oExcel.DisplayAlerts = False‗Open Book in Excel
Set oBook = oExcel.Workbooks.Open(sSrcPath)
‗Set Activesheet
Set oSheet = oExcel.Activesheet
‗Delete row range
oSheet.Columns(sStartCol + ―:‖ + sEndCol).Delete
‗Save new book to Excel file
oBook.SaveAs (sDestPath)
‗Close the xls file
oExcel.Workbooks.Close()
End Function
// ADODB CONNECTION TO READ DATA FROM EXCEL SHEET
Function obj_UDF_getRecordset (strFileName, strSQLStatement)
Dim objAdCon, objAdRs
Set objAdCon = CreateObject(―ADODB.Connection‖)
objAdCon.Open ―DRIVER={Microsoft Excel Driver (*.xls)};DBQ=―&strFileName &
―;Readonly=True‖
If Err <> 0 Then
Reporter.ReportEvent micFail,‖Create Connection‖, ―[Connection] Error has
occured. Error : ― & Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs = CreateObject(―ADODB.Recordset‖)
objAdRs.CursorLocation=3 ‗ set the cursor to use adUseClient -
disconnected recordset
objAdRs.Open strSQLStatement, objAdCon, 1, 3
MsgBox objAdRs.fields(4).name
While objAdRs.EOF=false
For i=0 to 4
varConcat= varConcat&‖ ―& objAdRs.fields(i)
Next
Reporter.ReportEvent 0,‖Here is the Full Contents‖,‖―& varConcat
varConcat=――
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 45
objAdRs.moveNext
Wend
If Err<>0 Then
Reporter.ReportEvent micFail,‖Open Recordset‖, ―Error has occured.Error Code : ―
& Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs.ActiveConnection = Nothing
objAdCon.Close
Set objAdCon = Nothing
Set obj_UDF_getRecordset = objAdRs
End Function
Set rsAddin = obj_UDF_getRecordset(―C:\Documents and
Settings\mohank\Desktop\Login.xls‖, ―Select * from [Login$]‖)
//Use the CompareFiles function
The following function can be used to check and compare the content of the two files.
Note:
This function is not part of QuickTest Professional/Astra QuickTest. It is not guaranteed
to work and is not supported by Mercury Interactive Technical Support. You are
responsible for any and all modifications that may be required.CompareFiles (FilePath1,
FilePath2)
FilePath1 The path to the first file to compare
FilePath2 The path to the second file to compare
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject(―Scripting.FileSystemObject‖)
If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)
CompareFiles = False
Do While File1.AtEndOfStream = False
Str1 = File1.Read(1000)
Str2 = File2.Read(1000)
CompareFiles = StrComp(Str1, Str2, 0)
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 46
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
File1.Close()
File2.Close()
End Function
Return value: The function returns 0 or False if the two files are identical, otherwise True.Example:
File1 = ―C:\countries\apple1.jpg‖
File2 = ―C:\countries\apple3.jpg‖
If CompareFiles(File1, File2) = False Then
MsgBox ―Files are identical.‖
Else
MsgBox ―Files are different.‖
End If
// GET NAMES OF ALL OPEN BROWSERS
Set browserDesc = Description.Create()
browserDesc(―application version‖).Value = ―internet explorer 6″
Set browserColl = DeskTop.ChildObjects(browserDesc)
browserCnt = browserColl.Count
MsgBox ―There are ―&browserCnt&‖ instances of a browser‖
For i = 0 To (browserCnt -1)
MsgBox ―Browser # ―&i&‖ has title = ―& browserColl(i).GetROProperty(―title‖)
Next ‗ i
Set browserColl = Nothing
Set browserDesc = Nothing
// How to run the scripts in 8.2 those are recorded in 9.0 or higher
Step 1: Delete the object repository of 9.0
Step 2: open a Blank test in 8.2
Step 3: Create the shared object repository in 8.2 that should contain all the objects in 9.0
and save.
Step 4: create the action structure in 8.2 should contain the same num of actions, same
names and structure as the script of 9.0.
Step 5: save the test. (From now we call this as 8.2 scripts)
Step 6: from 8.2 script copy Test.tsp file to the 9.0 script.
Step 7: copy all Resource.MTR file found in Action0, Action 1, etc to 9.0 scripts
Step 8: now u can run the scripts with little modifications if require
Automated Test Script Creation Process
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 47
Debugging and troubleshooting test scripts becomes extremely tedious when the
test script has hundreds of lines of code, verification points, branching logic, error
handling, parameters, and test correlation among various recorded business processes. A
more manageable approach to debugging complex and lengthy test scripts is to record
portions of the script and debug those portions individually before recording other parts
of the test script. After testing individual portions, you can determine how one portion of
the test script works with another portion and how data flows from one recorded process
to the other. After all sections for a test script have been recorded, you can playback the
entire test script and ensure that it properly plays back from the beginning to the end with
one or more sets of data.
Always create a test plan that will assist in the creation of the regression test
script. A test script is only as good as the planning that takes place before it is written.
This saves time and organizes the process.
Remember that all regression test scripts will be written to run in the QA
environment as well as the production environment. The automated regression test use
will be a part of the production test used to determine if a build truly does function as
expected in production.
To manage the creation and edit of our automated regression tests QA will create
automated tests in the following manner:
1. Record each individual process such as logging in and logging out. Save
those recordings on your desktop.
2. Verify that the script will play back with no errors.
3. Continue recording and playing back throughout the test script creation
process, verifying the script will play back with each step taken.
4. Add multiple sets of data driven tests for each individual portion of each
test where that kind of test is applicable.
5. Verify the individual test scripts with multiple sets of data will play back
with no errors.
6. Add various check points throughout the test.
7. Verify the individual test scripts with various check points will play
back with no errors.
8. Now integrate all recorded processes into one large test script.
9. Verify the large test script will play back with no errors.
The key here is to ensure that each recorded process plays back successfully before
proceeding to record the remaining portions of the entire test script. Do not string the
individual tests together for playback without first verifying that all of the processes
could play back successfully as individual processes.
Lesson to be learned here is to never, EVER wait to debug a script until the entire test
script has been recorded.
Synchronization
Since QTP can play back recorded test scripts much faster than an end-user‘s manual
keystrokes all tests must be synchronized. Introduce artificial wait times in the test
scripts to make sure the script will run appropriately without errors unattended. Take into
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 48
account the fact that there will be times when the script will need to run slower than a
manual test due to network issues, etc. The goal here is we want to make sure the scripts
will run unattended through Test Director. Slowing down a script with wait times is not
very scientific and does not contribute to the creation of a robust automated test script
that plays back successfully without user intervention. That said, sync times will be
edited after the test script has been written in its entirety and has been tested to ensure it
runs with no errors.
Signed-off, Peer Reviewed
As part of the test readiness review criteria, test scripts will be formally accepted and
approved prior to starting the test cycle. QA, Business Analysts and Developers should
be involved in approving recorded test scripts. The QA Analyst writing the automated
test script should demonstrate that the test script successfully plays back in the QA
environment and, if possible, with various sets of data.
Recording, Playing Back Against Hidden Objects
Scripts might be recorded to populate or double click values for a field within a table grid
or an array where the location of this field is not fixed. If the field‘s location within a
table grid or array changes from the time it was recorded, the script might fail during play
back. Test scripts often fail during play back because the locations of objects that are not
displayed or visible within the screen have changed.
In order to play back scripts that are location sensitive or where the location is subject to
change, it might be necessary to enhance the script with functionality such as ‗scroll
down‘, ‗next page‘, or ‗find‘. Including such utilities ensures that hidden objects
requiring play back will be identified, and/or double clicked regardless of their location
within an array, table grid, or the displayed screen.
Create Automatic Notification for Critical Scripts
Test scripts should be enhanced with error handling programming logic that instantly
sends error messages to a tester‘s e-mail address when problems occur. Since some test
scripts are business critical and must run as batch jobs in the middle of the night we need
to know if something failed as soon as possible. The proper and successful execution of
these business critical test scripts can serve as a dependency or pre-condition for other
automated tasks. Always include logic in business critical test scripts that automatically
sends notification in the event of a failure.
Documentation
To make test scripts reusable and easier to maintain, please document all relevant
information for executing the test script, a test script header, and any special conditions
for execution of the test script. Example:
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 49
1. Adjust dates within the application in QA environment for running
reports.
2. Update any fields that require unique data.
3. Display settings for context sensitive/analog/bitmap recording.
4. List other test scripts that are dependencies.
5. Specify necessary authorization levels or user roles for executing the
script.
6. Conditions under which the script can fail and work around for re-
launching the script.
7. Applications that need to be either opened or closed during the script
execution.
8. Specific data formats, etc.
Scripts should contain a header with a description (example: what it is used for) and its
particular purpose (example: regression testing). The script header should also include
the script author and owner, creation and modification date, requirement identifiers that
the script traces back to, the product the script supports and the number of variables and
parameters of the script. Providing this information in the test script header facilitates the
execution, modification, and maintenance of the script for future testing efforts.
//Descriptive Programming to find number of unread messages in yahoo mail
SystemUtil.Run"iexplore","http://www.yahoomail.com"
Set g=Browser("name:=Yahoo.*").Page("title:=Yahoo.*")
g.WebEdit("name:=login").Set "xyz"
g.WebEdit("name:=passwd").Set "abc"
g.WebButton("name:=Sign In").Click
a=g.Link("name:=Inbox.*").getroproperty("innertext")
b=len(a)
If b=5 Then
Msgbox"u have zero unread messages"
else
c=mid(a,8,len(a)-1)
d=left(c,len(c)-1)
msgbox "number of unread messages=" &d
End If
I can not read the unread mails no using the descriptive program
SystemUtil.Run"iexplore","http://www.yahoomail.com"
Set g=Browser("name:=Yahoo.*").Page("title:=Yahoo.*")
g.WebEdit("name:=login").Set "xyz"
g.WebEdit("name:=passwd").Set "abc"
g.WebButton("name:=Sign In").Click
a=g.Link("name:=Inbox.*").getroproperty("innertext")
b=len(a)
If b=5 Then
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 50
Msgbox"u have zero unread messages"
else
c=mid(a,8,len(a)-1)
d=left(c,len(c)-1)
msgbox "number of unread messages=" &d
End If
the following error
Run Error Cannot identify the object "[ Link ]" (of class Link). Verify that this object's
properties match an object currently displayed in your application.
Line (7): "a=g.Link("name:=Inbox.*").getroproperty("innertext")".
Failed 6/12/2008 - 14:12:22
Am using the New Version of Y!mail hope your script was for Old/Classic version
pl do change the script accordingly
// Orkut Login
Set IE=CreateObject("Internetexplorer.Application")
IE.Visible= True
IE.Navigate "www.orkut.com"
Set a=browser("name:=orkut.*").page("title:=orkut.*")
a.webedit("name:=Email").set"abc"
a.webedit("name:=Passwd").set"123"
a.webbutton("name:=Sign in").Click
a.Link("name:=Logout").Click
// Yahoo Login
SystemUtil.Run"iexplore","http://www.yahoomail.com"
Set g=Browser("name:=Yahoo.*").Page("title:=Yahoo.*")
g.WebEdit("name:=login").Set "aaa"
g.WebEdit("name:=passwd").SetSecure "bbb"
g.WebButton("name:=Sign In").Click
g.Link("name:=Inbox.*",
"html id:=WelcomeInboxFolderLink").Click
g.Link("name:=Sign Out").Click
SystemUtil.Run"iexplore","http://www.yahoomail.com" statement opens yahoo login
page
aaa=username
bbb=password
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 51
Over and above features provided with QTP 8.2, QTP 9.0 provides following features:
Object Repository Manager:
You can use the Object Repository Manager to manage all of the shared object repositories in your organization from one, central location. This includes adding and
defining objects, modifying objects and their descriptions, parameterize test object property
values, maintaining and organizing repositories, and importing and exporting repositories in
XML format. You can open multiple object repositories at the same time. Each object repository opens in
its own resizable document window. This enables you to compare the content of the
repositories, to copy or move objects from one object repository to another, and so forth.
Object Repository Merge Tool: You can use the Object Repository Merge Tool to merge the objects from two shared
object repositories into a single shared object repository. You can also use the Object Repository Merge Tool to merge objects from the local object repository of one or more
actions or components into a shared object repository.
When you merge objects from two source object repositories, the content is copied to a new,
target object repository, ensuring that the information in the source repositories remains unchanged.
If any conflicts occur during the merge, for example, if two objects have the same name and
test object class, but different test object descriptions, the relevant objects are highlighted in
the source repositories, and the Resolution Options pane details the conflict and possible resolutions.
Multiple Object Repositories per Action or Component: Quick Test provides several options for storing and accessing test objects. You can
store the test objects for each action or component in its corresponding local object
repository, which is unique for each action and component. You can also store test objects in
one or more shared object repositories that can be used in multiple actions and components. Alternatively, you can use a combination of objects from the local object repository and one
or more shared object repositories. You choose the combination that matches your testing
needs.
XML Object Repository Format:
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 52
Quick test now enables you to import and export object repositories from and to
XML format. This enables you to modify object repositories using the XML editor of your
choice and then import them back into Quick Test. You can import and export files either from and to the file system or a Quality Center project (if Quick Test is connected to Quality
Center).
Functions Library Editor:
Quick Test now has a built-in function library editor, which enables you to create and
edit function libraries containing VBScript functions, subroutines, modules, and so forth, and then call their functions from your test or component.
Handling Missing Actions and Resources: Whenever a testing document (test, component, or application area) contains a
resource that cannot be found, Quick Test opens the Missing Resources pane and lists the
missing resource(s). For example, a test may contain an action or a call to an action that
cannot be found; a testing document may use a shared object repository that cannot be found;
or a testing document may use an object repository parameter that does not have a default value. In all of these cases, Quick Test indicates this in the Missing Resources pane, enabling
you to map a missing resource to an existing one, or remove it from the testing document, as
required.
1) How to add a constant number in a data table? This is more to do with MS excel then QTP!! But useful to know because at times it becomes
frustrating to the novices. Just append ' to the number Ex: if you wish to enter 1234567 in data table then write it as '1234567
2) How can I check if a parameter exists in Data Table or not? The best way would be to use the below code: on error resume next
Val=DataTable ("ParamName", dtGlobalSheet)
if err. number<> 0 then 'Parameter does not exist
else 'Parameter exists end if
3) How can I check if a checkpoint passes or not? chk_PassFail = Browser (...).Page (...).WebEdit (...).Check (Checkpoint ("Check1"))
if chk_PassFail then MsgBox "Check Point passed" else MsgBox "Check Point failed"
end if
4) my test fails due to checkpoint failing, Can I validate a checkpoint without my test
failing due to checkpoint failure?
Reporter. Filter = rfDisableAll 'Disables all the reporting stuff
chk_PassFail = Browser (...).Page (...).WebEdit (...).Check (Checkpoint ("Check1")) Reporter. Filter = rfEnableAll 'Enable all the reporting stuff
if chk_PassFail then MsgBox "Check Point passed"
else MsgBox "Check Point failed" end if
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 53
5) What is the difference between an Action and a function? Action is a thing specific to QTP while functions are a generic thing which is a
feature of VB Scripting. Action can have an object repository associated with it while a
function can't. A function is just lines of code with some/none parameters and a single return
value while an action can have more than one output parameters.
6) Where to use function or action? Well answer depends on the scenario. If you want to use the OR feature then you
have to go for Action only. If the functionality is not about any automation script i.e. a function like getting a string between to specific characters, now this is something not
specific to QTP and can be done on pure VB Script, so this should be done in a function and
not an action. Code specific to QTP can also be put into a function using DP. Decision of
using function/action depends on what any one would be comfortable using in a given situation.
7) When to use a Recovery Scenario and when to us on error resume next? Recovery scenarios are used when you cannot predict at what step the error can occur
or when you know that error won't occur in your QTP script but could occur in the world
outside QTP, again the example would be "out of paper", as this error is caused by printer
device driver. "On error resume next" should be used when you know if an error is expected
and dont want to raise it, you may want to have different actions depending upon the error that occurred. Use err.number & err.description to get more details about the error.
8) How to use environment variable? A simple definition could be... it is a variable which can be used across the reusable
actions and is not limited to one reusable action. There are two types of environment
variables: 1. User-defined 2. Built-in
We can retrieve the value of any environment variable. But we can set the value of only user-defined environment variables. To set the value of a user-defined environment variable:
Environment (Variable Name) = NewValue To retrieve the value of a loaded environment
variable: CurrValue = Environment (VariableName) 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")
9) How to rename a checkpoint (QTP 9.0)? Example:
Window ("Notepad").WinEditor ("Edit").Check Checkpoint ("Edit") in the above example, the user would like to change the name of the Checkpoint object from "Edit" to something
more meaningful.
Note: This functionality is new to QuickTest Professional 9.0.This is not available for
QTP 8.2 and below. 1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object in
Expert View. 2. Select "Checkpoint Properties" from the pop-up menu. 3. In the Name field,
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 54
enter the new checkpoint name. 4. Click. The name of the checkpoint object will be updated
within the script.
Example: Window ("Notepad").WinEditor ("Edit").Check Checkpoint ("NewCheckPointName") Note: You must use the QuickTest Professional user interface to
change the name of the checkpoint. If you manually change the name of the checkpoint in the
script, QuickTest Professional will generate an error during replay. The error message will be
similar to the following: "The "" Checkpoint object was not found in the Object Repository. Check the Object
Repository to confirm that the object exists or to find the correct name for the object." The
Checkpoint object is not a visible object within the object repository, so if you manually modify the name, you may need to recreate the checkpoint to resolve the error.
Include the Windows Media Player's executable in the NoBBTApps section of the
mic.ini file 1. Close QuickTest Professional. 2. Go to \bin\mic.ini. 3. Include wmplayer.exe in the
NoBBTApps section of mic.ini file. Example: [NoBBTApps] wmplayer.exe=rek
4. Save the mic.ini file and restart QuickTest Professional.
13) What is the lservrc file in QTP? The lservrc file contains the license codes that have
been installed The lservrc file contains the license codes that have been installed. Whenever a new license is
created, the license code is automatically added to this file. The lservrc file is a text file, with
no extension.
File Location: 1) For a Concurrent (Floating) license installation:
"#server installation directory#\#language#"
Example: C:\Program Files\XYZ Technologies\ABC Server\English\lservrc 2) For a Seat (Stand-alone) license installation:
#AQT/QTP installation directory#\bin"
Example: C:\Program Files\Mercury Interactive\QuickTest Professional\Bin\lservrc
14) What to do if you are not able to run QTP from quality center? This is for especially for newbie‘s with QTP. Check that you have selected Allow other
mercury products to run tests and components from Tools--> Options--> Run Tab.
Test objects are the objects in your test that represent the objects in your website or application. Runtime objects are the objects in your application during the test run. The Test
object properties set is created and maintained by QuickTest. The Runtime object property
set is created and maintained by the object creator (Microsoft for Internet Explorer objects,
Netscape for Netscape objects, the product developer for ActiveX objects, etc.).
Descriptive Programming:
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 55
Whenever QTP records any action on any object of an application, it adds some description
on how to recognize that object to a repository of objects called object repository. QTP
cannot take action on an object until unless its object description is in the Object Repository. But descriptive programming provides a way to perform action on objects which are not in
Object repository.
When and Why to use Descriptive programming?
Below are some of the situations when Descriptive Programming can be considered useful:
1. The objects in the application are dynamic in nature and need special handling to identify the object. The best example would be of clicking a link which changes according to the user
of the application, Ex. ―Logout <>‖.
2. When object repository is getting huge due to the no. of objects being added. If the size of
Object repository increases too much then it decreases the performance of QTP while recognizing an object.
3. When you don‘t want to use object repository at all. Well the first question would be why
not Object repository? Consider the following scenario which would help understand why not
Object repository Scenario 1: Suppose we have a web application that has not been developed yet.Now QTP for recording the script and adding the objects to repository needs
the application to be up, that would mean waiting for the application to be deployed before
we can start of with making QTP scripts. But if we know the descriptions of the objects that
will be created then we can still start off with the script writing for testing
Scenario 2: Suppose an application has 3 navigation buttons on each and every page. Let the
buttons be ―Cancel‖, ―Back‖ and ―Next‖. Now recording action on these buttons would add 3 objects per page in the repository. For a 10 page flow this would mean 30 objects which
could have been represented just by using 3 objects. So instead of adding these 30 objects to
the repository we can just write 3 descriptions for the object and use it on any page. 4.
Modification to a test case is needed but the Object repository for the same is Read only or in shared mode i.e. changes may affect other scripts as well.
5. When you want to take action on similar type of object i.e. suppose we have 20 textboxes
on the page and there names are in the form txt_1, txt_2, txt_3 and so on. Now adding all 20
the Object repository would not be a good programming approach.
How to use Descriptive Programming?
There are two ways in which descriptive programming can be used 1. By creating properties
collection object for the description. 2. By giving the description in form of the string arguments.
Arrays
An array is a contiguous area in the memory referred to by a common name. It is a
series of variables having the same data type. Arrays are used to store related data values.
VBScript allows you to store a group of common values together in the same location. These values can be accessed with their reference numbers.
An array is made up of two parts, the array name and the array subscript. The subscript
indicates the highest index value for the elements within the array. Each element of an array
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 56
has a unique identifying index number by which it can be referenced. VBScript creates zero
based arrays where the first element of the array has an index value of zero.
Declaring Arrays An array must be declared before it can be used. Depending upon the accessibility, arrays are
of two types:
· Local Arrays A local array is available only within the function or procedure, where it is declared.
· Global Arrays
A global array is an array that can be used by all functions and procedures. It is declared at the beginning of the VBScript Code.
The Dim statement is used to declare arrays. The syntax for declaring an array is as follows:
Dim ArrayName(subscriptvalue) Where, ArrayName is the unique name for the array and SubscriptValue is a numeric value
that indicates the number of elements in the array dimension within the array.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 57
Example:
Dim No_Passengers(3)
The No_Passengers can store 4 values.
Assigning values to the array No_Passengers(0) = 1
No_Passengers(1) = 2 No_Passengers(2) = 3
No_Passengers(3) = 4
Static and Dynamic Arrays: VBScript provides flexibility for declaring arrays as static or dynamic.
A static array has a specific number of elements. The size of a static array cannot be altered
at run time. A dynamic array can be resized at any time. Dynamic arrays are useful when size of the array
cannot be determined. The array size can be changed at run time.
Next we will deal with user defined procedures, functions and subroutines.
I have seen an umpteen no of posts in every QTP group I visited asking about Test Automation frameworks. Here I would like to collate the useful inputs i received from
How do we associate a library file with a test ?
• Library files are files containing normal VBScript code. The file can contain
function, sub procedure, classes etc…. You can also use executefilefunction to include a file at run-time also. To associate a library file with your script go to Test->Settings… and add your library file to resourcestab.
When to associate a library file with a test and when to use execute file?
• When we associate a library file with the test, then all the functions within that library are available to all the actions present in the test. But when we use Executefile
function to load a library file, then the function is available in the action that called
executefile. By associated a library toa test we share variables across action (global
variables basically), using association also makes it possible to execute code as soon as the script runs because while loading the script on startup QTP executes all the
code on the global scope. We can use executefile in a library file associated with the
test to load dynamic files and they will be available to all the actions in the test.
Test and Run-time Object What is the difference between Test Objects and Run Time Objects ?
• Test objects are basic and generic objects that QTP recognize. Run time object means the actual object to which a test object maps.
Can i change properties of a test object
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 58
• Yes. You can use SetTOProperty to change the test object properties. It is recommended that you switch off the Smart Identification for theobject on which you use SetTOProperty function.
Can i change properties of a run time object?
• No (but Yes also). You can use GetROProperty(”outerText”) to get the outerText of a object but there is no function like SetROProperty tochange
this property. But you can use WebElement().object.outerText=”Something” to change the property.
Action & Functions what is the difference between an Action and a function?
• Action is a thing specific to QTP while functions are a generic thing which is a
feature of VB Scripting. Action can have a object repositoryassociated with it while a function can’t. A function is just lines of code with some/none
parameters and a single return value while an action canhave more than one output parameters.
Where to use function or action?
• Well answer depends on the scenario. If you want to use the OR feature then you have to go for Action only. If the functionality is not about any automation script i.e. a
function like getting a string between to specific characters, now this is something not
specific to QTP and can be done onpure VB Script, so this should be done in a
function and not an action. Code specific to QTP can also be put into an function using DP. Decision of using function/action depends on what any one would be
comfortable using in a given situation.
Checkpoint & Output value What is checkpoint?
• Checkpoint is basically a point in the test which validates for truthfulness of a specific things in the AUT. There are different types ofcheckpoints depending on the type of data that needs to be tested in the AUT. It can be text, image/bitmap, attributes, XML etc….
What’s the difference between a checkpoint and output value?
• Checkpoint only checks for the specific attribute of an object in AUT while
Output value can output those attributes value to a column in datatable.
How can i check if a checkpoint passes or not?
chk_PassFail = Browser(…).Page(…).WebEdit(…).Check
(Checkpoint(”Check1″))
if chk_PassFail then
MsgBox “Check Point passed”
else
MsgBox “Check Point failed”
end if
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 59
My test fails due to checkpoint failing, Can i validate a checkpoint without my test failing due to checpoint failure? Reporter.Filter = rfDisableAll „Disables all the reporting stuff
chk_PassFail = Browser(…).Page(…).WebEdit(…).Check
(Checkpoint(”Check1″))
Reporter.Filter = rfEnableAll „Enable all the reporting stuff
if chk_PassFail then
MsgBox “Check Point passed”
else
MsgBox “Check Point failed”
end if
Environment How can i import environment from a file on disk
• Environment.LoadFromFile “C:\Env.xml” How can i check if a environment variable exist or not?
• When we use Environment(‖Param1″).value then QTP expects the environment
variable to be already defined. But when we useEnvironment.value(‖Param1″)
then QTP will create a new internal environment variable if it does not exists
already. So to be sure that variable existin the environment try using
Environment(‖Param1″).value
1. How Does Run time data (Parameterization) is handled in QTP? A) You can then enter test data into the Data Table, an integrated spreadsheet with the full functionality of Excel, to manipulate data sets and create multiple test iterations, without programming, to expand test case coverage. Data can be typed in
or imported from databases, spreadsheets, or text files. 2) What is keyword view and Expert view in QTP? A) QuickTest’s Keyword Driven approach, test automation experts have full access to
the underlying test and object propertyes, via an integrated scripting and debugging environment that is round-trip synchronized with the Keyword View. Advanced testers can view and edit their tests in the Expert View, which reveals the underlying industry-standard VBScript that QuickTest Professional automatically generates. Any
changes made in the Expert View are automatically synchronized with the Keyword View. 3) Explain about the Test Fusion Report of QTP ?
A) Once a tester has run a test, a TestFusion report displays all aspects of the test run: a high-level results overview, an expandable Tree View of the test specifying exactly where application failures occurred, the test data used, application screen shots for every step that highlight any discrepancies, and detailed explanations of each checkpoint pass and failure. By combining TestFusion reports with QuickTest
Professional, you can share reports across an entire QA and development team. 4) To which environments does QTP supports ?
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 60
QuickTest Professional supports functional testing of all enterprise environments, including Windows, Web, ..NET, Java/J2EE, SAP, Siebel, Oracle, PeopleSoft, Visual Basic, ActiveX, mainframe terminal emulators, and Web services. 11) In how many ways we can add check points to an application using QTP. A) We can add checkpoints while recording the application or we can add after recording is completed using Active screen (Note : To perform the second one The
Active screen must be enabled while recording). 12) How does QTP identifes the object in the application A) QTP identifies the object in the application by LogicalName and Class. For example: The Edit box is identified by Logical Name: PSOPTIONS_BSE_TIME20
Cass: WebEdit 13) If an application name is changes frequently i.e while recording it has name “Window1” and then while running its “Windows2” in this case how
does QTP handles? A) QTP handles those situations using “Regular Expressions”. 14) What is Parameterizing Tests?
A) When you test your application, you may want to check how it performs the same operations with multiple sets of data. For example, suppose you want to check how your application responds to ten separate sets of data. You could record ten separate tests, each with its own set of data. Alternatively, you can create a parameterized
test that runs ten times: each time the test runs, it uses a different set of data.
Handling Run Errors in QTP
The Run Error message box displayed during a run session offers a number of buttons for
dealing with errors encountered:
Stop—Stops the run session.
The run results are displayed if QuickTest is configured to show run results after
the run.
Retry—QuickTest attempts to perform the step again.
If the step succeeds, the run continues.
Skip—QuickTest skips the step that caused the error, and continues the run from
the next step.
Debug—QuickTest suspends the run, enabling you to debug the component and
any associated function library that contains a function called by the component.
You can perform any of the debugging operations described in this section. After
debugging, you can continue the run session from the step where the component
or function library stopped, or you can use the step commands to control the
remainder of the run session.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 61
Help—Opens the QuickTest troubleshooting Help for the displayed error
message. After you review the Help topic, you can select another button in the
error message box.
Details—Expands the message box to display additional information about the
error.
How to use Watch in QTP??
You can view the current value of any variable or VBScript object in your function
library by adding it to the Watch tab. As you continue stepping into the subsequent steps
in your function library, QuickTest automatically updates the Watch tab with the current
value for any object or variable whose value changes. You can also change the value of
the variable manually when the function library pauses at a breakpoint.
To add an expression to the Watch tab:
Perform one of the following:
Click the expression and choose Debug > Add to Watch
Click the expression and press CTRL+T
Right-click the expression and choose Add to Watch from the context menu
In the Watch tab, paste or type the name of the object or variable into the Name
column and press ENTER to view the current value in the Value column
Note: You can add an expression to the Watch tab from a function library (and not from
a business component).
Tip: You can also use the Variables tab to view the current values for all variables up to
the current step in the function library.
Run Error: Test run failed
Q: Run Error: Test run failed
The run session cannot continue due to an unknown error. Check the step where the
failure occurred.
If your component failed while referring to an external file, such as an associated
function library, check that the files are accessible from your computer and that the files
are saved in the appropriate format.
If your component failed while performing a QuickTest step in a function, refer to the
QuickTest Object Model Reference for more information on appropriate usage of the
function in your statement.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 62
If your component failed while performing a standard VBScript step in a function, refer
to the Microsoft VBScript Reference.
Run Error: The object's item is not unique
Q: Why this error occurs??
More than one item in a list or tree item has the name specified in the method argument.
Specify the item using the item's index (for example, "#4"). Note that different test
objects and methods may use a different syntax for specifying an item's index.
Run Error: Cannot identify item
QuickTest cannot identify a list or tree item specified in a method argument.
Confirm that the specified item exists in the object.
If the object does not exist, delete the step or modify the item on which you want
to perform the step.
If the item exists, its name may have changed. Modify the name as necessary or
specify the item using the item's index (for example, "#4"). Note that different test
objects and methods may use a different syntax for specifying an item's index.
Run Error: Parent not found
Each object in your component is identified relative to its parent objects.
If you received a Parent not found message, try one of the following solutions:
Fix the object description of the problematic parent object using the suggestions
below
o If you find that an object in your component has one or more property
values in its description that differs from the corresponding object
property in your application, determine whether the problem is with an
individual object in your application, or whether the same problems apply
to all or many of the objects in your application with the same object class.
Find all instances of the old hierarchy in the Expert View and replace it with the
correct object hierarchy as described below
Re-recording an Object to Identify Parent Object Description
Problems
Follow the instructions below to identify a problem with a parent object.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 63
To identify a problem with a parent object by re-recording the child object:
1. Open your browser or application to the page containing the object that caused the
error.
2. Select the last step in the component in the Keyword View or place the cursor
below the last statement in the Expert View.
3. Click the Record button or choose Automation > Record.
4. Click or perform another operation on the object.
5. Click the Stop button or choose Automation > Stop.
6. Right-click the new step and select Object Properties.
7. In the Object Properties dialog box, click Repository. The Object Repository
opens with the new object selected. Note the parent hierarchy of the new object.
8. Find the old (problematic) object in the Object Repository and compare the parent
hierarchy of the old object with that of the new object.
Check to see whether the differences are due to one or more parent objects with
different descriptions, or whether the actual objects in the parent hierarchy are
different.
o If you find a problem with a parent description, try to fix it using the
suggestions for Solving Object Description Problems.
o If the problem stems from a different set of parent objects in the hierarchy,
find all instances of the old hierarchy and replace it with the new object
hierarchy as described in the example below.
Example:
Suppose that on a Web site with frames, you recorded a step on an Image object named
Poster. In the Object Repository window, you can see that Image object's hierarchy is
similar to the following (the object class is listed in parentheses for this example):
MyCompany (Browser)
MyCompany (Page)
Main (Frame)
Poster (Image)
When you later run the component, the Web page looks the same, but you receive a
Cannot Identify Object error for the Poster image. When you re-record the step and view
the Image object in the Object Repository window, the hierarchy might look like this:
MyCompany (Browser)
MyCompany (Page)
Poster (Image)
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 64
Now you can see that the frames have been removed from the Web page, so even though
the Poster image still has the same object description, its parent hierarchy is different.
In the object repository, you can see that there are actually two different poster objects:
the old one under the obsolete Frame object, and the new one directly under the
MyCompany page.
To fix the problem, you can replace the object in the step by clicking Select another
object and choosing the required object from the correct location in the hierarchy (tree).
To keep your Object Repository well-organized, you should also delete the obsolete
objects from the Object Repository by right-clicking the obsolete object and selecting
Delete.
Using Microsoft Outlook to Send Email
The code below illustrates two methods for sending email using the VBScript code in
QuickTest Professional, and two different COM objects.
' Example 1
Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function
' Example 2
Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
ObjMail.Send
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 65
Set objMail = Nothing
End Function
// To Close all Browsers Except One Gmail
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
Set oPage = Description.Create
oPage("micclass").Value = "Page"
'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
Dim i, iCount
iCount = allBrowser.Count
Msgbox iCount
For i = 0 To iCount-1
'Get the page object from the browser
'Set oPg = allBrowser(i).ChildObjects(oPage)
'Get the URL of the
Msgbox allBrowser(i).GetRoProperty("title")
If InStr(1,allBrowser(i).GetRoProperty("title"),"Gmail", vbTextCompare) = 0 Then
'Close the browser
allBrowser(i).Close
End If
Next
// To Close all Browsers Except One Gmail
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
Set oPage = Description.Create
oPage("micclass").Value = "Page"
'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
Dim i, iCount
iCount = allBrowser.Count
Msgbox iCount
For i = 0 To iCount-1
'Get the page object from the browser
'Set oPg = allBrowser(i).ChildObjects(oPage)
'Get the URL of the
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 66
Msgbox allBrowser(i).GetRoProperty("title")
If InStr(allBrowser(i).GetRoProperty("title"),"Gmail") = 0 Then
'Close the browser
allBrowser(i).Close
End If
Next
// To Close all Browsers except Quality Center
'Create a description for browser
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
Set oPage = Description.Create
oPage("micclass").Value = "Page"
'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
Dim i, iCount
iCount = allBrowser.Count - 1
For i = 0 To iCount
'Get the page object from the browser
Set oPg = allBrowser(i).ChildObjects(oPage)(0)
'Get the URL of the
If InStr(oPg.GetROProperty("title"), "Quality Center", vbTextCompare) = 0
Then
'Close the browser
allBrowser(i).Close
End If
Next
By now you must be wondering about the line
'Get the page object from the browser
Set oPg = allBrowser(i).ChildObjects(oPage)(0)
// script to check all checkboxes in a webpage.
Set a=Description.Create
a("html tag").value="input"
a("type").value="checkbox"
Set b=Browser("name:=").Page("title:=").childobjects(a)
c=b.count
msgbox c
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 67
For i=0 to c-1
b(i).set "on"
Next
// To Close all Browsers
Call Closebrowser()
Function Closebrowser
While Browser("CreationTime:=.*").Exist
Browser("CreationTime:=.*").Close
Wend
End Function
//To Close QTP after execution
Private Function CloseQTP
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where
Name = 'QTPro.exe'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
Set objWMIService = Nothing
Set colProcess = Nothing
End Function
Call CloseQTP
//
Set Desc= description.Create()
desc("micclass").value ="WebCheckBox"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 68
msgbox data(i).getroproperty("name")
Next
//
Set Desc= description.Create()
desc("micclass").value ="WebEdit"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
//
Set Desc= description.Create()
desc("micclass").value ="WebRadioButton"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
//
Set Desc= description.Create()
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 69
desc("micclass").value ="WebButton"
Set data=Browser("name:=127.0.0.1").Page("title:=127.0.0.1").ChildObjects(desc)
s=data.count()
msgbox "Buttons" & VBNewLine &s
For i = 0 to s - 1
msgbox data(i).getroproperty("name")
Next
//
Dim vcol_Handles, vCtr, vHwnd, Flag, vLastHWnd
vCtr = 0
Flag = 1
Set vcol_Handles = CreateObject("Scripting.Dictionary")
While (Window("regexpwndclass:=IEFrame","index:=" & vCtr).Exist )
wait 1
vHwnd = Window("regexpwndclass:=IEFrame","index:=" &
vCtr).getroproperty("Hwnd")
If (vLastHWnd=vHwnd) Then
Flag = 0
Else
vcol_Handles.Add CStr(vcol_Handles.Count),vHwnd
vCtr = vCtr+1
End If
vLastHWnd = vHwnd
msgbox vLastHWnd
Wend
msgbox vCtr
For vCtr = vcol_Handles.Count-1 to 0 step-1
Wait 1
vHwnd = vcol_Handles.Item(CStr(vCtr))
vBrowser = Window("regexpwndclass:=IEFrame","index:=" &
vCtr).getroproperty("text")
If Instr(vBrowser, "Mercury") then
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 70
Reporter.ReportEvent 2, "Not closed " & vBrowser, "The browser '" & vBrowser & "'
was not closed"
Else
Reporter.ReportEvent 2, "Closed " & vBrowser, "The browser '" & vBrowser & "' was
closed"
Window("hwnd:=" & vHwnd).Close
End If
Next
In above code use SystemUtil.CloseProcessByHwnd (vHwnd)
instead of Window("hwnd:=" & vHwnd).Close, because .Close won't work if you have
popups.
Also replace the following lines:
vBrowser = Window("regexpwndclass:=IEFrame","index:=" &
vCtr).getroproperty("text")
If Instr(vBrowser, "Mercury") then
vBrowser = Window("regexpwndclass:=IEFrame","hwnd:="&
vHwnd).getroproperty("text")
If Instr(vBrowser, "Mercury Quality")<>0 OR Instr(vBrowser, "TestDirector")<>0 then
You can also give a try with this code:
do while("True")
TrueOrFalse = Browser("opnedbytestingtool:=True").Exist
if(TrueOrFalse = "False") then
exit do
else
Browser("opnedbytestingtool:=True").close
end if
loop
This works:
Do while("True")
TrueOrFlase = Browser("index:=0").Exist
if(TrueOrFlase = "False") then
exit do
else
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 71
'if Browser("index:=0").Window("regexpwndclass:=Internet
Explorer_TridentDlgFrame").exist(5) then
' Browser("index:=0").Window("regexpwndclass:=Internet
Explorer_TridentDlgFrame").close
' TIM - I changed the .exist period from 5 to 1 to, hopefully, speed up this process.
if Browser("index:=0").Dialog("nativeclass:=#32770").exist(1) then
Browser("index:=0").Dialog("nativeclass:=#32770").close
end if
Browser("index:=0").close
end if
loop
The above code will close all the browser that are opened.
Here instead of creation time other ordinal identifier can also be used.
Dim windows2Close
'Initialize with negative upper bound
ReDim windows2Close( -1)
'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
'Get all open windows collection
Set allWins = shlApp.Windows
'Loop through each window and close if IE
For Each window In allWins
'Close all IE windows but ignore Quality Center
If InStr(window.fullName, "iexplore.exe") And InStr(Window.LocationURL,
"/qcbin/") = 0 Then
'Increase the array size by 1
ReDim Preserve windows2Close(UBound(windows2Close) + 1)
Set windows2Close(UBound(windows2Close)) = Window
End If
Next
'Loop through all array elements and close each window
For Each Window In windows2Close
Window.Quit
Next
'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
'Get all open windows collection
Set allWins = shlApp.Windows
'Loop through each window and close if IE
For Each window In allWins
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 72
If InStr(window.fullName, "iexplore.exe") Then
'Close the IE window
window.Quit
End If
Next
'Launch a notepad window
SystemUtil.Run "notepad.exe"
'Close the window just launched using the exact title
SystemUtil.CloseProcessByWndTitle "Untitled - Notepad"
'Launch a notepad window
SystemUtil.Run "notepad.exe"
'Close the window just launched using a pattern string
SystemUtil.CloseProcessByWndTitle ".*Notepad", True
SystemUtil.CloseDescendentProcesses
CloseDescendentProcesses can be used to close any process launched by QTP. The code
below illustrates the usage
'Launch explorer
SystemUtil.Run "iexplore.exe"
'Launch excel using COM
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True
'Close processes launched by QTP. This will close
'the internet explorer and Excel as well
SystemUtil.CloseDescendentProcesses
'Close all internet explorer windows
closedCount = SystemUtil.CloseProcessByName("iexplore.exe")
'Display # of closed windows
MsgBox closedCount
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 73
'Run internet explorer
SystemUtil.Run "iexplore.exe"
'Run internet explorer and open knowledgeinbox.com
SystemUtil.Run "iexplore.exe", "http://www.knowledgeinbox.com"
'Run a IE Process in Maximized window
Const SHOW_MAXIMIZED = 3 'Activates the window and displays it as a maximized
window.
SystemUtil.Run "iexplore.exe", "http://www.knowledgeinbox.com", , ,
SHOW_MAXIMIZED
1. Getting Number from String
Function extract_number(msg) Dim re, matches, item, result
Set re = New RegExp
re.pattern = "[A-Za-z -.]*(\d+).*"
Set matches = re.Execute(msg)
If matches.Count > 0 Then
Set item = matches(0)
If item.SubMatches.Count > 0 Then
result = item.SubMatches(0)
Else
result = -1
End If
Else
result = -1
End If
extract_number = result
End Function
MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")
2. Close All the opened Browsers Except QC opened browser
On Error Resume Next
Dim intWndCnt
Dim oDesc, oWnd
'Create Object description
Set oDesc = Description.Create '
Set oWnd = Desktop.ChildObjects(oDesc)
intWndCnt = oWnd.Count
For i = 0 to intWndCnt - 1
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 74
Set TmpObj = oWnd.item(i)
strTmpTitle = oWnd.item(i).GetROProperty("Text")
If instr(1,strTmpTitle, "Microsoft Internet Explorer",1) > 0 Then
If instr(1,strTmpTitle, "Mercury Quality Center",1) > 0 Then
'msgbox "Title :" & oWnd.item(i).GetROProperty("Text")
Else
'msgbox "Close :" & oWnd.item(i).GetROProperty("Text")
oWnd.item(i).close
End if
End If
Next
'Clean up
Set oDesc = nothing
Set oWnd = nothing
3. Close all opened Excel files
Public Function fn_close_all_excel_files()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where
Name = 'EXCEL.EXE'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
End Function
4. Excel sheet column count
Public Function dtGetColCount (sSheetName)
On Error Resume Next
Do
i = i + 1
sColName = DataTable.GetSheet(sSheetName).GetParameter(i).Name
Loop While 0 = Err.Number
'GetParameter throws an error when using an index that is out of bounds ...
'We can use this functionality to ASSUME that it's an unused column.
'We've come to the end of our USED columns
dtGetColCount = i - 1
On Error GoTo 0
End Function
5. Count Number of files in any Folder
iFileCount = 0
Set objFileSysOb = CreateObject("Scripting.FileSystemObject")
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 75
Set colFolderName = objFileSysOb.GetFolder("C:\Automation") ' Folder Path
Set vFiles =colFolderName.Files
For each vFileItem in vFiles
print vFileItem
iFileCount = iFileCount + 1
Next
print iFileCount
6. Create Dynamic Array
For i = 0 to 20
Redim Preserve arrFileLines(i)
arrFileLines(i) = "test" & i
Next
7. Close Dialog box
Function DialogClose (obj) If obj.Dialog("nativeclass:=#32770").Exist(0) Then
obj.Dialog("nativeclass:=#32770").WinButton("nativeclass:=Button","index:=0").Click
End If
RegisterUserFunc "Browser", "DialogClose", "DialogClose"
End Function
8. Create Dynamic Value
iDynamicValue = now
iDynamicValue = replace(iDynamicValue,"/","")
iDynamicValue = replace(iDynamicValue,":","")
iDynamicValue = replace(iDynamicValue," ","")
iDynamicValue = replace(iDynamicValue,"PM","")
iDynamicValue = replace(iDynamicValue,"AM","")
msgbox iDynamicValue
9. Get QTP file path
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application
objectqtpApp.Test.Location
TestLoc = qtApp.Test.Location
MsgBox TestLoc
10. IS QC Connected?
Set qtApp = CreateObject("QuickTest.Application")
If qtApp.TDConnection.IsConnected Then
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 76
msgbox "QC"
Else
msgbox "Local"
End If
(or)
if QCUtil.IsConnected then
Reporter.ReportEvent 0, "Connected", "Connected to server: " +
QCUtil.QCConnection.ServerName + chr (13) +"Project: " +
QCUtil.QCConnection.ProjectName + chr (13) + "Domain: " +
QCUtil.QCConnection.DomainName
else
Reporter.ReportEvent 1, "Not connected", "Not connected to Quality Center"
end if
11. Keyboard Key Press through QTP Script
'Create Shell Object
Set WshShell = CreateObject("WScript.Shell")
'Send any Functinal Keys
' ALT = %
' F4 = {F4}
WshShell.SendKeys "%{F4}"
' Set shell object to Null
Set WshShell=nothing
1. BEEP from QTP
' Three methods of issuing a BEEP from QTP
' Method 1 Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
retVal = Extern.MessageBeep(&HFFFFFFFF)
MsgBox retVal 'The return value should be 1.
' Method 2
Err.Number = 0
On Error Resume Next
Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
Extern.MessageBeep(&HFFFFFFFF)
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 77
If (Err.Number <> 0) Then
MsgBox Err.Description
End If
' Method 3
Extern.Declare micLong,"Beep","Kernel32","Beep",micLong,micLong
retVal = Extern.Beep(1000,250) 'The first number is frequency the second is duration.
MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")
2. Check for Required URL
startURL = "www.google.com" ' Amend this to your required URL
' If no browser open, open browser and navigate to required URL
If Not Browser("CreationTime:=0").Exist Then
Call launch(startURL)
Else
' Get the URL of the current open browser
currentURL=Browser("CreationTime:=0").GetROProperty("OpenURL")
' If not correct URL navigate to required URL
If Not currentURL = "www.google.com" Then
Call launch(startURL)
End If
End If
Function launch(startURL)
' Create IE object and navigate
' to required URL
set IE = CreateObject("InternetExplorer.Application")
IE.Visible = true
IE.Navigate startURL
End function
3. Close QTP with QTP script
Private Function CloseQTP Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where
Name = 'QTPro.exe'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 78
Set objWMIService = Nothing
Set colProcess = Nothing
End Function
4. Open any Appllication through QTP
' Function OpenApp
' ------------------
' Open a specified application
' Parameter: application - the application full name (including location)
'@Description Opens an application
'@Documentation Open the application.
Function OpenApp (application)
systemUtil.Run application
End Function
5. Adding any information to QTP Results
' AddToTestResults
' --------------
' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event '
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.
Public Function AddToTestResults (status, StepName, details)
Reporter.ReportEvent status, StepName, details
End Function
6. Enable Doubleclick Event in QTP
Enable the ondblclick event in the Web Event Recording Configuration
To enable special event handling, use the Web Event Recording Configuration utility.
1. Go to Tools -> Web Event Recording Configuration.
2. Click .
3. Expand the Standard Objects branch.
4. Select the object you want to configure.
5. Go to Event -> Add -> ondblclick. The event will be added to the list on the right.
6. Select "If Handler" in the Listen column.
7. Select "Enabled" in the Record column.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 79
8. Click to close the dialogs.
7. DSN - Less Connection
Public sconn
uid = "UID"
pwd = "PWD"
ServerName = "Server Name"
Connection()
Function Connection() Set sconn = CreateObject("ADODB.connection")
sconn.Open "Driver=Microsoft ODBC for Oracle;Server="& ServerName &";Uid="&
uid &";Pwd="& pwd &""
End Function
8. High-Level Automation Framework Information
At a very high level the framework components can be divided into two categories
software part and documentation part. Here is my list of components ? you can add your
item if anything is missing.
---------------------------------------------
All software code part
---------------------------------------------
Supporting libraries for Logging, error handling, Execution management
1. Tool specific code
2. Setup and configuration scripts
3. Test management code
4. Test data and Test data management code
5. Platform/OS specific scripts
---------------------------------------------
Non software part
---------------------------------------------
Folder structure
Documents
i. Coding guidelines
ii. Procedure for creating scripts
iii. Planning, design and review procedures
iv. Approach for automation
v. Approach for Testing automation code
vi. Automation documentation - how scripts work
vii. Setup and implementation procedures
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 80
viii. Defect tracking procedure for Automation scripts
ix. Source control procedures
x. Project plan
xi. Templates for effort estimation
xii. Template for test case categorization
xiii. Template for ROI calculation
9. Get Input Parameter Data and Use in Script
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
Set pDefColl = qtApp.Test.ParameterDefinitions
Set pDef = pDefColl.Item(1)
MsgBox pDef.DefaultValue
10. Pass Test Data from MQC to QTP?
1) Create Test parameters in QTP (via file>Settings>Parameters) [These are the
parameters that you see in QC, on the automated tab of the Configuration page in the Test
Instance Propertirs.]
2) Create action parameters (Action Properties> Parameters)
3)Link action & test parameters together. To do this, go into Action Call
Properties>Parameters. You'll see your action parameters here. Click in the Value column
for a parameter and press the Configure Value button. This will open up the Value
Configuration Options dialogue. In the parameter drop down list, select Test/action
parameter and then, from the following Test parameters; Parameter drop down list, select
the Test parameter that you want to link to your Action parameter.
This should then link the Test parameters to the Action parameters.
Then in your script, you'll use the parameters as follows: -
Browser("Browser_Name").Page("Page_Name").WebEdit("Edit_Name").Set
Parameter("Parameter_Name")
11. Get the Attachement from QC to local machine
To get attachment from test
Public Function GetTestAttachmentPath(TDAttachmentName) 'Returns File Path
'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 81
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaExtendedStorage 'As TDAPIOLELib.ExtendedStorage
Dim strPath 'As String
Set otaAttachmentFactory = QCUtil.CurrentTest.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
otaAttachmentFilter.Filter("CR_REFERENCE") = "'TEST_" & QCUtil.CurrentTest.Id &
"_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count = 1 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
ElseIf otaAttachmentList.Count > 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _
"Found more than one attachment '" & TDAttachmentName & "' in test '" & _
QCUtil.CurrentTest.Name & "'."
strPath = ""
ElseIf otaAttachmentList.Count < 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _
"Found 0 attachments '" & TDAttachmentName & "' in test '" & _
QCUtil.CurrentTest.Name & "'."
strPath = ""
End If
GetTestAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing
End Function
To get attachment from folder
Public Function GetFolderAttachmentPath(TDAttachmentName, TDFolderPath) 'Returns
File Path
'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaTreeManager 'As TDAPIOLELib.TreeManager
Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 82
Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
Dim intNdId
Dim strPath 'As String
Set otaTreeManager = QCUtil.TDConnection.TreeManager
Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
Set otaAttachmentFactory = otaSysTreeNode.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
intNdId = otaSysTreeNode.NodeID
otaAttachmentFilter.Filter("CR_REFERENCE") = "'ALL_LISTS_" & intNdId & "_" &
TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count > 0 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
Else
Reporter.ReportEvent micFail,"Failure in library function 'GetFolderAttachmentPath'", _
"Failed to find attachment '" & TDAttachmentName & "' in folder '" & TDFolderPath &
"'."
End If
GetFolderAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing
Set otaTreeManager = Nothing
Set otaSysTreeNode = Nothing
End Function
1. Can I change the Active Screen which is shown on every new test?
You can change the Active Screen to any valid HTML page. The page can be located
either locally or on the network.
For example, if you want your entire organization to view the same Active Screen when
opening QuickTest Professional, open the NewTest.inf file located in QuickTest
Professional\dat\SnapShots folder and add the following line:
FileName1= "any full path to an HTML file"
For example:
FileName1=\mercury\public\MainPage.html
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 83
2. How do I create an action template?
If you want to include one or more statements in every new action in your test, you can
create an action template. For example, if you always enter your name as the author of an
action, you can add this comment line to your action template. An action template applies
only to actions created on your computer.
To create an action template, create a text file containing the comments, function calls,
and other statements that you want to include in your action template. The text file must
be in the structure and format used in the Expert View.
Save the text file as ActionTemplate.mst in your QuickTest Professional\dat folder. All
new actions you create contain the script lines from the action template.
3. How can I configure the report to show only errors by default?
You can configure the report to show only errors by default by adding the following
section to the QTReport.ini file in your QuickTest Professional\bin folder.
[FilterDialog]
ReportAppDefaultFilter=1 # for error only
ReportAppDefaultFilter=3 # shows all messages (default)
4. How do I use environment variables?
QuickTest supports using environment variables. Environment variables can be either
system variables or user-defined variables.
You can define the user-defined variables in an external file QuickTest reads when it is
launched.
5. I have a Microsoft Access database that contains data I would like to use in my
test. How do I do this?
The Expert View enables you to access databases using ADO and ODBC. Below is a
sample test that searches for books written by an author in the "Authors" table of the
database.
Dim MyDB
Dim MyEng
Set MyEng = CreateObject("DAO.DBEngine.35")
Dim Td
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 84
Dim rs
' Specify the database to use.
Set MyDB = MyEng.OpenDatabase("BIBLIO.MDB")
' Read and use the name of the first 10 authors.
Set Td = MyDB.TableDefs("Authors")
Set rs = Td.OpenRecordset
rs.MoveFirst
For i = 1 To 10
Browser("Book Club").Page("Search Books").WebEdit("Author Name").Set
rs("Author")
Browser("Book Club").Page("Search Books").WebButton("Search").Click
Next
6. How do I add a manual wait step to my test?
A manual wait (think time) can be added to a QuickTest Professional test using the
following command:
Call Wait()
7. How do I make the test prompt the user for input while it is running?
The VBScript InputBox function enables you to display a dialog box that prompts the
user for input and then continues running the test. You can use the value that was entered
by the user later in the test. For more information on the InputBox function, refer to the
VBScript Reference.
The following example shows the InputBox function used to prompt the user for a
password.
Browser("Mercury Tours").Page("Mercury Tours").WebEdit("username").Set
"administrator"
Passwd = InputBox ("Enter password", "User Input")
Browser("Mercury Tours").Page("Mercury Tours").WebEdit("password").Set Passwd
8. How can I configure the report to show only errors by default?
You can configure the report to show only errors by default by adding the following
section to the QTReport.ini file in your QuickTest Professional\bin folder.
[FilterDialog]
ReportAppDefaultFilter=1 # for error only
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 85
ReportAppDefaultFilter=3 # shows all messages (default)
9. How can I remove test result files from old tests?
You can use the Test Results Deletion Tool to view a list of all the test results in a
specific location in your file system or in a Quality Center project. You can then delete
any test results that you no longer require.
The Test Results Deletion Tool enables you to sort the test results by name, date, size,
and so forth, so that you can easily identify the results you want to delete.
You can find this utility in Start > Programs > QuickTest Professional > Tools > Test
Results Deletion Tool.
10. How can I launch a new browser from a test?
A new browser window (and any other application) can be launched from within a test by
adding the following step to your test:
SystemUtil.Run "iexplore.exe", "http://www.testingfaqs.co.in"
11. How can I record on nonstandard menus?
You can modify how QuickTest behaves when it records menus.
The options that control this behavior are located in the Advanced Windows Applications
Options dialog box. (Tools > Options > Windows Applications > Advanced).
12. How can I terminate an application that is not responding?
You can terminate any standard application while running a test in QuickTest by adding
one of the following steps to the test:
SystemUtil.CloseProcessByName "app.exe"
SystemUtil.CloseProcessByWndTitle "Some Title"
13. Can I copy and paste to and from the Clipboard during a test run?
You can use the Clipboard object to copy, cut, and paste text during a QuickTest test run.
The object has the same methods as the Clipboard object available in Visual Basic:
Clear
GetData
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 86
GetFormat
GetText
SetData
SetText
Below is an example of Clipboard object usage:
Set MyClipboard = CreateObject("Mercury.Clipboard")
MyClipboard.Clear
MyClipboard.SetText "TEST"
MsgBox MyClipboard.GetText
14. How do I close QuickTest after "n" test runs when running from Quality
Center?
When running multiple QuickTest tests from Quality Center, you can specify that you
want to close QuickTest after a specified number of tests are executed.
To do so, add the following lines to the end of the mic.ini file, located in your QuickTest
Professional\bin folder:
[RemoteAgent]
CloseToolAfterRuns= (number)
15. Adding Defects to Quality Center
Connects to Quality Center (TestDirector) from a QuickTest test and adds a bug to the
database.
Dim TDConnection
Set TDConnection = CreateObject("TDApiOle.TDConnection")
TDConnection.InitConnection "http://yovav/tdbin" ' URL for the DB
TDConnection.ConnectProject "TD76","bella","pino" ' Valid login information
If TDConnection.Connected Then
MsgBox("Connected to " + chr (13) + "Server " + TDConnection.ServerName _
+ chr (13) +"Project " + TDConnection.ProjectName )
Else
MsgBox("Not Connected")
End If
'Get the IBugFactory
Set BugFactory = TDConnection.BugFactory
'Add a new empty bug
Set Bug = BugFactory.AddItem (Nothing)
'Fill the bug with relevant parameters
Bug.Status = "New"
Bug.Summary = "Connecting to TD"
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 87
Bug.Priority = "4-Very High" ' depends on the DB
Bug.AssignedTo = "admin" ' user that must exist in the DB's users list
Bug.DetectedBy = "admin" ' user that must exist in the DB's users list
'Post the bug to database (commit)
Bug.Post
16. Using Message Boxes That Close Automatically
The function below shows a message box that disappears after the specified timeout (in
seconds). The script execution then continues.
Public Sub MsgBoxTimeout (Text, Title, TimeOut)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Popup Text, TimeOut, Title
End Sub
If TimeOut is 0, it behaves just like a normal message box. If TimeOut is greater than 0,
the dialog box disappears after the specified number of seconds.
17. Using Microsoft Word Spell Check
The following code shows a function for checking the number of spelling and grammar
errors in a string. This function is also used to check the accuracy of a specific property in
all the objects of a given application.
Function NumberOfSpellErrors(strText)
Dim objMsWord
Set objMsWord = CreateObject("Word.Application")
objMsWord.WordBasic.FileNew
objMsWord.WordBasic.Insert strText
NumberOfSpellErrors = objMsWord.ActiveDocument.SpellingErrors.Count
objMsWord.Documents.Close (False)
objMsWord.Quit ' close the application
Set objMsWord = Nothing' Clear object memory
End Function
' The following function uses the Spell errors function to check a specific property
' of all the objects with a given description which are under a given parent
Sub CheckAllObjects(ParentObj, ObjDesc, PropName)
Dim ObjCol, idx, PropValue, OldReportMode
OldReportMode = Reporter.Filter
Reporter.Filter = 2 ' Report only errors
If (IsNull(ParentObj)) Then
Set ObjCol = Desktop.ChildObjects(ObjDesc)
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 88
Else
Set ObjCol = ParentObj.ChildObjects(ObjDesc)
End If
For idx=0 to ObjCol.count-1
PropValue = ObjCol.Item(idx).GetROProperty(PropName)
RetVal = NumberOfSpellErrors(PropValue) ' The actual spell check result
If (RetVal > 0) Then
ReportText = "Object #" & idx+1 & ": The '" & PropName & "' Property has " & RetVal
& " spell errors (" & PropValue & ")"
Reporter.ReportEvent 1, "Spell Check", ReportText
End If
Next
Reporter.Filter = OldReportMode
End Sub
'''''''''''''''''''''''''''''''''''''
' An example of usage:
' Go over all the static objects in the Login window of the Flight Application
' and for each object check the text for spelling and grammatical errors
'''''''''''''''''''''''''''''''''''''
' Go over all the links in the page and report all the ones that fail the spellcheck
Set Desc = Description.Create()
Desc("nativeclass").Value = "Static"
Set Obj = Dialog("nativeclass:=#32770", "text:=Login")
' Invoke the Flight Application before calling the function
CheckAllObjects Obj, Desc, "text"
18. Using Microsoft Outlook to Send Email
The code below illustrates two methods for sending email using the VBScript code in
QuickTest Professional, and two different COM objects.
' Example 1
Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 89
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function
' Example 2
Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
ObjMail.Send
Set objMail = Nothing
End Function
19. DP Example
SetEditBox "userID", 0, "Sairam"
Sub SetEditBox(ObjName, index, TestData)
strHandle = Window("RegExpWndClass:=IEFrame","index:=0"
).GetROProperty("hWnd")
Set gobjBrowser = Browser("hWnd:=" & strHandle)
Set gobjPage = gobjBrowser.Page("index:=0")
Set objDescription = Description.Create()
objDescription("Class Name").Value = "WebEdit"
objDescription("html tag").Value = "INPUT"
objDescription("name").Value =ObjName
objDescription("index").Value = index
gobjPage.WebEdit(objDescription).Set TestData
set gobjBrowser = nothing
Set gobjPage = nothing
End Sub
20. SaveAs Excel file with QTP
Set xl = CreateObject("Excel.Application")
xl.visible = True
xl.Application.Workbooks.open "C:\sai.xls"
xl.Worksheets(1).Activate
xl.Application.Visible = True
xl.Cells(1,1).Value = "mum"
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 90
xl.Cells(1,2).Value = "dad"
xl.activeworkbook.SaveAs("C:\sai1.xls")
xl.Application.Quit
// Excel
Dim ExcelApp 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Dim excelBook 'As Excel.workbook
Dim fso 'As Scripting.FileSystemObject
' This function will return a new Excel Object with a default new Workbook
Function CreateExcel() 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Set ExcelApp = CreateObject("Excel.Application") 'Create a new excel Object
ExcelApp.Workbooks.Add
ExcelApp.Visible = True
Set CreateExcel = ExcelApp
End Function
'This function will close the given Excel Object
'excelApp - an Excel application object to be closed
Sub CloseExcel(ExcelApp)
Set excelSheet = ExcelApp.ActiveSheet
Set excelBook = ExcelApp.ActiveWorkbook
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.CreateFolder "C:\Temp"
fso.DeleteFile "C:\Temp\ExcelExamples.xls"
excelBook.SaveAs "C:\Temp\ExcelExamples.xls"
ExcelApp.Quit
Set ExcelApp = Nothing
Set fso = Nothing
Err = 0
On Error GoTo 0
End Sub
'The SaveWorkbook method will save a workbook according to the
workbookIdentifier
'The method will overwrite the previously saved file under the given path
'excelApp - a reference to the Excel Application
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 91
'workbookIdentifier - The name or number of the requested workbook
'path - the location to which the workbook should be saved
'Return "OK" on success and "Bad Workbook Identifier" on failure
Function SaveWorkbook(ExcelApp, workbookIdentifier, path) 'As String
Dim workbook 'As Excel.workbook
On Error Resume Next
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
On Error GoTo 0
If Not workbook Is Nothing Then
If path = "" Or path = workbook.FullName Or path = workbook.Name Then
workbook.Save
Else
Set fso = CreateObject("Scripting.FileSystemObject")
'if the path has no file extension then add the 'xls' extension
If InStr(path, ".") = 0 Then
path = path & ".xls"
End If
On Error Resume Next
fso.DeleteFile path
Set fso = Nothing
Err = 0
On Error GoTo 0
workbook.SaveAs path
End If
SaveWorkbook = "OK"
Else
SaveWorkbook = "Bad Workbook Identifier"
End If
End Function
'The SetCellValue method sets the given 'value' in the cell which is identified by
'its row column and parent Excel sheet
'excelSheet - the excel sheet that is the parent of the requested cell
'row - the cell's row in the excelSheet
'column - the cell's column in the excelSheet
'value - the value to be set in the cell
Sub SetCellValue(excelSheet, row, column, value)
On Error Resume Next
excelSheet.Cells(row, column) = value
On Error GoTo 0
End Sub
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 92
'The GetCellValue returns the cell's value according to its row column and sheet
'excelSheet - the Excel Sheet in which the cell exists
'row - the cell's row
'column - the cell's column
'return 0 if the cell could not be found
Function GetCellValue(excelSheet, row, column)
value = 0
Err = 0
On Error Resume Next
tempValue = excelSheet.Cells(row, column)
If Err = 0 Then
value = tempValue
Err = 0
End If
On Error GoTo 0
GetCellValue = value
End Function
'The GetSheet method returns an Excel Sheet according to the sheetIdentifier
'ExcelApp - the Excel application which is the parent of the requested sheet
'sheetIdentifier - the name or the number of the requested Excel sheet
'return Nothing on failure
Function GetSheet(ExcelApp, sheetIdentifier) 'As Excel.worksheet
On Error Resume Next
Set GetSheet = ExcelApp.Worksheets.Item(sheetIdentifier)
On Error GoTo 0
End Function
'The InsertNewWorksheet method inserts an new worksheet into the active
workbook or
'the workbook identified by the workbookIdentifier, the new worksheet will get a default
'name if the sheetName parameter is empty, otherwise the sheet will have the sheetName
'as a name.
'Return - the new sheet as an Object
'ExcelApp - the excel application object into which the new worksheet should be added
'workbookIdentifier - an optional identifier of the worksheet into which the new
worksheet should be added
'sheetName - the optional name of the new worksheet.
Function InsertNewWorksheet(ExcelApp, workbookIdentifier, sheetName) 'As
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 93
Excel.worksheet
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
'In case that the workbookIdentifier is empty we will work on the active workbook
If workbookIdentifier = "" Then
Set workbook = ExcelApp.ActiveWorkbook
Else
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
Set InsertNewWorksheet = Nothing
Err = 0
Exit Function
End If
On Error GoTo 0
End If
sheetCount = workbook.Sheets.Count
workbook.Sheets.Add , sheetCount
Set worksheet = workbook.Sheets(sheetCount + 1)
'In case that the sheetName is not empty set the new sheet's name to sheetName
If sheetName <> "" Then
worksheet.Name = sheetName
End If
Set InsertNewWorksheet = worksheet
End Function
'The RenameWorksheet method renames a worksheet's name
'ExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
'sheetName - the new name for the worksheet
Function RenameWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier,
sheetName) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Workbook Identifier"
Err = 0
Exit Function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 94
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Worksheet Identifier"
Err = 0
Exit Function
End If
worksheet.Name = sheetName
RenameWorksheet = "OK"
End Function
'The RemoveWorksheet method removes a worksheet from a workbook
'ExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
Function RemoveWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier) 'As
String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Workbook Identifier"
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Worksheet Identifier"
Exit Function
End If
worksheet.Delete
RemoveWorksheet = "OK"
End Function
'The CreateNewWorkbook method creates a new workbook in the excel application
'ExcelApp - the Excel application to which an new Excel workbook will be added
Function CreateNewWorkbook(ExcelApp)
Set NewWorkbook = ExcelApp.Workbooks.Add()
Set CreateNewWorkbook = NewWorkbook
End Function
'The OpenWorkbook method opens a previously saved Excel workbook and adds it
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 95
to the Application
'excelApp - the Excel Application the workbook will be added to
'path - the path of the workbook that will be opened
'return Nothing on failure
Function OpenWorkbook(ExcelApp, path)
On Error Resume Next
Set NewWorkbook = ExcelApp.Workbooks.Open(path)
Set OpenWorkbook = NewWorkbook
On Error GoTo 0
End Function
'The ActivateWorkbook method sets one of the workbooks in the application as
Active workbook
'ExcelApp - the workbook's parent excel Application
'workbookIdentifier - the name or the number of the workbook
Sub ActivateWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Activate
On Error GoTo 0
End Sub
'The CloseWorkbook method closes an open workbook
'ExcelApp - the parent Excel application of the workbook
'workbookIdentifier - the name or the number of the workbook
Sub CloseWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Close
On Error GoTo 0
End Sub
'The CompareSheets method compares between two sheets.
'if there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'"Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - the excel sheets to be compared
'startColumn - the column to start comparing in the two sheets
'numberOfColumns - the number of columns to be compared
'startRow - the row to start comparing in the two sheets
'numberOfRows - the number of rows to be compared
Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow,
numberOfRows, trimed) 'As Boolean
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 96
Dim returnVal 'As Boolean
returnVal = True
'In case that one of the sheets doesn't exists, don't continue the process
If sheet1 Is Nothing Or sheet2 Is Nothing Then
CompareSheets = False
Exit Function
End If
'loop through the table and fill values into the two worksheets
For r = startRow to (startRow + (numberOfRows - 1))
For c = startColumn to (startColumn + (numberOfColumns - 1))
Value1 = sheet1.Cells(r, c)
Value2 = sheet2.Cells(r, c)
'if 'trimed' equels True then used would like to ignore blank spaces
If trimed Then
Value1 = Trim(Value1)
Value2 = Trim(Value2)
End If
'in case that the values of a cell are not equel in the two worksheets
'create an indicator that the values are not equel and set return value
'to False
If Value1 <> Value2 Then
Dim cell 'As Excel.Range
sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is
'" & Value1 & "'."
Set cell = sheet2.Cells(r, c)
cell.Font.Color = vbRed
returnVal = False
End If
Next
Next
CompareSheets = returnVal
End Function
// To Check File Exist or Not
Function ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
ReportFileStatus = msg
End Function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 97
Or
filePath="c:\testlog.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filePath)) Then
Msgbox "File Exists at : " &filePath
Else
Msgbox "File doesn't exist at :" &filePath
End If
// Folder Exists
Function ReportFolderStatus(fldr)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
msg = fldr & " exists."
Else
msg = fldr & " doesn't exist."
End If
ReportFolderStatus = msg
End Function
Or
fldr="c:\wmpub"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
Msgbox "Folder exists at :" &fldr
Else
Msgbox "Folder doesn't exist at :" &fldr
End If
// File Created at Date
Function ShowFileInfo(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
ShowFileInfo = "Created: " & f.DateCreated
End Function
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 98
Or
filespec="c:\testlog.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
Msgbox "Created: " & f.DateCreated
// To Check File Extension
Function GetAnExtension(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAnExtension = fso.GetExtensionName(Drivespec)
End Function
Or
Drivespec="c:\testlog.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
GetAnExtension = fso.GetExtensionName(Drivespec)
Msgbox GetAnExtension
// Regular Expression
Function SubMatchTest(inpStr)
Dim oRe, oMatch, oMatches
Set oRe = New RegExp
' Look for an e-mail address (not a perfect RegExp)
oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
' Get the Matches collection
Set oMatches = oRe.Execute(inpStr)
' Get the first item in the Matches collection
Set oMatch = oMatches(0)
' Create the results string.
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 99
' The Match object is the entire match - [email protected]
retStr = "Email address is: " & oMatch & vbNewline
' Get the sub-matched parts of the address.
retStr = retStr & "Email alias is: " & oMatch.SubMatches(0) ' dragon
retStr = retStr & vbNewline
retStr = retStr & "Organization is: " & oMatch. SubMatches(1)' xyzzy
SubMatchTest = retStr
End Function
MsgBox(SubMatchTest("Please send mail to [email protected]. Thanks!"))
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches ' Create variable.
Set regEx = New RegExp ' Create a regular expression.
regEx.Pattern = patrn ' Set pattern.
regEx.IgnoreCase = True ' Set case insensitivity.
regEx.Global = True ' Set global applicability.
Set Matches = regEx.Execute(strng) ' Execute search.
For Each Match in Matches ' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))
// To Send Mail from outlook Application
SendTo="[email protected]"
SendToCC="[email protected]"
Subject="QTP mail"
Body1="This mail is generated from QTP Environment"
Attachment="C:\Spec.xls"
Call SendMail(SendTo, Subject, Body1, Attachment)
Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
'ol.DisplayAlerts = False
Mail.to=SendTo
Mail.CC=SendToCC
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 100
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function
// Automation Object Model (From Command Line )
Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtTest 'As QuickTest.Test ' Declare a Test object variable
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
qtApp.Launch ' Start QuickTest
qtApp.Visible = True ' Make the QuickTest application visible
qtApp.Open "C:\Temp\simple_test", True ' Open the test in read-only mode
' set run settings for the test
Set qtTest = qtApp.Test
qtTest.Run ' Run the test
WScript.StdOut.Write "Status is:" & qtTest.LastRunResults.Status ' Check the results of
the test run
qtTest.Close ' Close the test
Set qtResultsOpt = Nothing ' Release the Run Results Options object
Set qtTest = Nothing ' Release the Test object
Set qtApp = Nothing ' Release the Application object
C:\\cscript /nologo filename.vbs
How to use automation object to load the library
Dim qtApp
Dim qtLibraries
Set qtApp = CreateObject("QuickTest.Application")
Set qtLibraries = qtApp.Test.Settings.Resources.Libraries ' Get the libraries collection
object
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 101
If qtLibraries.Find("C:sai1.vbs") = -1 Then ' If the library cannot be found in the
collection
ExecuteFile "C:sai1.vbs"
End If
Call test1()
Function In File Sai1.vbs
Function test1()
MsgBox "Hi Manish"
End Function
How to use automation object to load the library
Store the Library file along with the entire path in a variable.
EG: sPath = "D:/Files/Functions.vbs"
Executfile (sPath)
OR
Executfile ("D:/Files/Functions.vbs")
Below this call which ever function you want to call from the library file
Call FunctName(argument list)
Can a function return dictonary object
Yes.
Functions can return a dictonary object.
Dim dicObj
Set dicObj = CreateObject("Scripting.Dictionary")
Set obj=getname
MsgBox(obj.item("name"))
Public Function getname()
dicObj.add "name","Uday Kumar"
Set getname=dicObj
End function
How the Message Boxes Close Automatically
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 102
The following script shows a message box that disappears after the specified timeout (in
seconds). The script execution then continues.
If TimeOut is 0, it behaves just like a normal message box. If TimeOut is greater than 0,
the dialog box disappears after the specified number of seconds.
Set wShellObj=createobject("WScript.shell")
wShellObj.popup "Hello Uday, How are you",10,"This is sample" ' Displays like this:
The message box automatically closes after 10 sec.s
Even we can handle the error messages from the error handling mechanism like this:
Set fileSysObj=createobject("Scripting.filesystemobject")
On Error resume next
fileSysObj.opentextfile("c:uday.txt")
str=Err.description
wShellObj.popup str,3,"This is for file not found"
How to find out the number of links in a web page
Here i am writing the link names in a text file
Set fileSysObject=createobject("Scripting.FileSystemObject")
Set linksFileName=fileSysObject.opentextfile("D:samplelinkfile.txt",2,true)
Set linkDescObj=description.Create
linkDescObj("micclass").value="Link"
Set noOfLinks=browser("Browser").Page("Yahoo! India").ChildObjects(linkDescObj)
For i=0 to noOfLinks.count-1
linkName=noOfLinks(i).getROProperty("name")
linksFileName.writeline(linkName)
Next
linksFileName.close
Set fileSysObject=nothing
VLearn Technologies www.mysaptesting.com
Name: Govind Mail ID: [email protected] Address: Namdev block, Plot No: 502, Prime Hospital Lane, Hyderabad Page 103
How to specify the environment variables to be loaded when QTP is started
You can either define individual values in the .vbs file or specify an environment file to
load.
Example: Here is what the .vbs file could look like:
Dim App ‗As Application
‗ Launch QTP
Set App = CreateObject(‖QuickTest.Application‖)
App.Launch
App.Visible = True
‗ Load an INI file with user-defined parameters
App.Test.Environment.LoadFromFile ―C:\Test_Params\environment_file1.ini‖
‗ Set the value of a specific user-defined Environment variable
App.Test.Environment.Value(‖newvariable‖) = ―new value‖
As you can see from the example, the Environment variable file is actually an .ini file.
The structure would be:
[Environment]
var1=value1
var2=value2
…