Vous êtes sur la page 1sur 166

1) Which environments are supported by QTP?

QTP supports the following environments


Active X
People Soft
Terminal Emulator
Delphi
Power Builder
Visual Basic
Java
SAP
Visual Age
.Net
Siebel
Web
Oracle
Stingray
Web Services
2) What are the types object Repositories in QTP.
QTP Supports 2 types of Object Repository
1) Shared Object Repository (also called Global)
2) Per-Action Object Repository, (also called Local)
Per-Action Object Repository is used by default. The extension for Per-Action repository
is ".mtr" .
Shared Object Repository is preferable while dealing with dynamic objects which are
called in multiple tests. The extension is ".tsr"
3) Can we call QTP test from another test using scripting. Suppose there are 4 tests and I
want to call these tests in a main script. Is this possible in QTP?
Yes. You can call 4 or even more scripts in your tests.For this, first you will need to
make the Actions in the corresponding scripts re-usable.Then from the destination
script you can make calls to these re-usable actions.
4) What is action split and the purpose of using this in QTP?
Action split is to divide an existing action into two parts.The purpose is to divide actions
based on their functionality to improve code re-use.
5) How will you handle Java tree in QTP ?
Foremost you will select Java Add - In and launch QTP. Next step record operations on
the Java Tree. If you face an issue while recording, you can select Tools > Object
Identification > Java, tree object and make changes in mandatory and assistive
properties to enable identification.
Tip: You can base you answer on similar lines for any other object of any environment.
For example : If the question is how will check SAP checkbox , You say , first I will select
SAP Add in ... and so on.
6) Explain how QTP identifies object ?
QTP identifies any GUI Object based on its corresponding properties. While recording,
QTP will identify and store peculiar properties (as defined in the Object Identification
settings) in the object repository of the GUI object . At run-time, QTP will compare the
stored property values with the on-screen properties, to uniquely identify the GUI
object.
7) How many types of recording modes in QTP? Which will be used when ?
QTP supports 3 types of recording modes
1. Normal mode also called Contextual
2. Low-level recording mode
3.Analog mode
Normal Mode: It is the default recording mode and takes full advantage of QTP's Test
Object Model. It recognizes objects regardless of their position on -screen. This is the
preferred mode of recoding and is used for most of the automation activities.
Low-level recording mode: This mode records the exact x,y co-ordinates of your mouse
operations. It is helpful in testing hashmaps. It is useful for recording objects not
identified by normal mode of QTP.

Analog mode: This mode records exact mouse and keyboard "movements" you perform
in relation to the screen / application window. This mode is useful for the operation
such as drawing a picture, recording signature., drag and drop operations.
8) How will you call from one action to another action ?
We can call an action in 2 ways
1) Call to copy of Action. - In this ,the Action Object Repository , Script and Datable will
be copied to the destination Test Script.
2) Call to Existing Action. - In this, Object Repository , Script and Datable will NOT be
copied but a call (reference) would be made to the Action in the source script.
10) How to perform Cross platform testing and Cross browser testing using QTP? Can u
explain giving some example?
You will need to create separate Actions which take care of different OS and Browsers
Cross Platform Testing:
Using the Built in Environment Variable you can dig up the OS information.
Eg. Platform = Environment("OS"). Then based on the Platform you need to call the
actions which you recorded on that particular platform.
Cross Browser Testing:
Using this code Eg. Browser("Core Values").GetROProperty("version") you can extract
the Browser and its correspondin version. Ex: Internet Explorer 6 or Netscape 5. Based
on this value you call the actions which are relevant to that browser.
For i=0 To 1
If i=0 Then
myBrowser = "IE"
myBrowserpath = "iexplore.exe"
ElseIf i=1 Then
myBrowser = "FF"
myBrowserpath = "firefox.exe"
Set App = CreateObject("QuickTest.Application")
App.Visible = True
App.Test.Settings.Launchers("Web").Act... = False
App.Test.Settings.Launchers("Web").Bro... = myBrowser
systemutil.Run myBrowserpath ,"http://studyautomation.com"
If Browser("Study Automation - A Community").Page("Study Automation - A
Community").Link("Home").Exist Then
Reporter.ReportEvent micPass,myBrowser &" Test","Passed"
Else
Reporter.ReportEvent micFail,myBrowser &" Test","Failed"
End If
Next
11) What is logical name of the object?
Logical name is a name given by QTP while creating an object in the repository to
uniquely identify it from other objects in the application. This name would be used by

the QTP to map the object name in script with its corresponding description in the
object repository. Ex: Browser("Browser").Page("Guru99") Here Guru99 is the logical
name of the object.
12) What is descriptive programming?
Typically ,an object and its properties must be recorded in the Object Repository to
enable QTP to perform action s on it.
Using descriptive programming , you do not store the object and its property values in
the Object repository but mention the property value pair directly in the script.
The idea behind descriptive programming is not bypass the object repository but help
recogonize dynamic objects.
13)What are the properties you would use for identifying a browser & page when using
descriptive programming ?
You can use the name property
ex: Browser("name:="xxx"").page("name:="xxxx"").....
OR
We can also use the property "micClass".
ex: Browser("micClass:=browser").page("micClass:=page")....
14)Can we record an application running on a remote machine using QTP ?
Yes .you can record remote application provided you are accessing application through
the local browser not via remoter like citrix.If you are still unable to record it is
advisable install QTP and application, on the same machine
15) Explain the keyword CreateObject with an example.
Creates and returns a reference to an Automation object
SYNTAX: CreateObject(servername.typename [, location])
Arguments
servername: Required. The name of the application providing the object.
typename : Required. The type or class of the object to create.
location : Optional. The name of the network server where the object is to be created.
Example : Set IE = CreateObject("InternetExplorer.Application")
16) Can you switch between Per-Action and Shared Object Repository ? If yes how ?
Yes .We can switch. Go to Test--->Settings--->Resources. Here you have an option to
choose repositories.
17) What is Object Spy ? How to Use it ?
Object Spy helps in determining the run & test time object properties & methods of the
application under test.You can access object spy directly from the toolbar or from the
Object Repository Dialog Box.It is very useful during Descriptive Programming
18) When ordinal identifiers alone can make an object unique then why they are not
given top priority? Why it is first mandatory and next assistive. Why we cannot go for
ordinal identifiers directly?
Consider the following -a) If two objects are overlapped on each other than location
based object recognition will fail.b) If only index based recognition is used your script
will work but script execution time will increase.Hence mandatory and assistive
properties are used.
19) What is the file extension of the code file in QTP?
Code file extension is script.mts
20) Explain in brief about the QTP Automation Object Model.

QTP Automation Object model deals with Automation of QTP itself. Almost all
configuration and functionality provided by QTP is represented by QTP's Automation
Object Model . Almost all dialog boxes in QTP have a corresponding automation object
which can set or retrieved using the corresponding properties or methods in the
Automation Object Model.QTP Automation Objects can be used along with standard VB
programming elements like iterative loops or conditional statements to help you design
a script of choice.
21) What is the use of Text output value in QTP?
Text Output values enable you to capture text appearing on the application under test
during run-time.
If parameterized, text output values will capture values appearing in each iteration
which would be stored in the run-time data table for further analysis.
22) What is Step Generator?
Step Generator enables use to Add Test Steps in your script. Using step generator you
can add steps to your script without actually recording it.
23) How to make QTP understand the difference amongst the same type of objects
.Suppose there are 5 check boxes in a page and I have to choose the 2nd one, how to do
that through script?
You can use ordinal identifiers like index along with a little descriptive programming for
object recognition.
24) What is Test Fusion Report ?.
Test Fusion Report , displays all aspects of a test run and is organized in a Tree format.
It gives details of each step executed for all iterations.
It also gives Run-time data table, Screen shots and movie of the test run if opted.
26) What are the types of environment variables in QTP ?
Environment variables in QTP are of three types:
1) Built-in (Read only)
2) User-defined Internal (Read only)
3) User-defined External (Read/Write)
You Set the Environment Variable using the following syntax
Environment.Value( "name") = "Guru99"
You can Retrieve the Environment Variable using following syntax
Environment.Value("name") -- This will retrun name as Guru99
Environment.Value("OS") -- This will return your system OS
27) What is the Difference between Bitmap Check point & Image Check point?
Bitmap checkpoint does a pixel to pixel comparison of an image or part of an image.
Image checkpoint does do a pixel to pixel comparison but instead compare image
properties like alt text , destination url etc.
28) What is the difference between functions and actions in QTP?
Actions have their own Object Repository & Data Table. Actions help make your Test
modular and increase reuse. Example: You can divide your script into Actions based on
functionality like Login, Logout etc.
Functions is a VB Script programming concept and do not have their own Object
Repository or Data Table. Functions help in re-use of your code. Ex: You can create a
Function in your script to concatenate two strings.
29) What is keyword view and Expert view in QTP?
Keyword View is an icon based view which shows test steps in tabular format. It also
automatically generates documentation for the test steps.

Expert View gives the corresponding VB Script statement for every test step in the
Keyword view.
30) Explain QTP Testing process? Quick Test testing process consists of 6 main phases:
1) Create your test plan - This is preparatory phase where you identify the exact test
steps, test data and expected results for you automated test. You also identify the
environment and system configurations required to create and run your QTP Tests.
2) Recording a session on your application - During this phase , you will execute test
steps one by one on your AUT ,and QTP will automatically record corresponding VB
script statements for each step performed.
3) Enhancing your test - In this stage you will insert checkpoints , output values ,
parameterization , programming logic like ifelse loops to enhance the logic of your test
script.
4) Replay & Debug - After enhancements you will replay the script to check whether its
working properly and debug if necessary.
5) Run your Tests - In this phase you will perform the actual execution of your Test
Script.
6) Analyzing the test results - Once test run is complete, you will analyze the results in
the Test Fusion report generated.
7) Reporting defects - Any incidents identified needs to be reported. If you are
usingQuality Center , defects can be automatically raised for failed tests in QTP.
31) What are the different types of Test Automation Frameworks ?
The types of Automation Frameworks are 1) Linear Scripting - Record & Playback
2) The Test Library Architecture Framework.
3)The Data-Driven Testing Framework.
4)The Keyword-Driven or Table-Driven Testing Framework.
32) How will you check a web application for broken links using QTP?
You can use the Page Checkpoint which gives a count of valid/invalid links on a page.
33) What is a Run-Time Data Table? Where can I find and view this table?
Data like parameterized output , checkpoint values , output values are stored in the
Run-time Table. It is an xls file which is stored in the Test Results Folder. It can also be
accessed in the Test Fusion Report.
34) What is the difference between check point and output value.
Check point is a verification point that compares a current value for a specified property
with the expected value for that property. Based on this comparison, it will generate a
PASS or FAIL status.
An output value is a value captured during the test run and can be stored in a specified
location like the Datable or even a variable. Unlike Checkpoints, no PASS/FAIL status is
generated.
35) How would you connect to database using vbscript ?
To connect to the database you must know
a) connection string of your server
b) username
c) password
d) DNS name
You can code the database connectivity command directly or you can use the SQLQuery
tool provided by QTP.
36) What is QTP batch testing tool?

You can use the Batch testing tool to run multiple scripts. Once the scripts are added in
the tool , it will automatically open the scripts and start executing them one after the
other.
37) What are the drawbacks of QTP?
As of QTP version 10
1) Huge Tests in QTP consume lots of memory and increase CPU utilization.
2) Since QTP stores results in HTML file (and not txt) the result folder sometimes
becomes big.
38) What is an Optional Step ?
A step when declared optional is not mandatory to be executed. If the corresponding
GUI object is present, QTP performs the operation on it. If the GUI object is not present,
QTP bypasses the optional step and proceeds to execute the next step.
39) What is Reporter.ReportEvent ?
Reporter.Reportvent is standard method provided by QTP to send custom messages to
the test results window.
Syntax
Reporter.ReportEvent EventStatus, ReportStepName, Details [, ImageFilePath]
where
EventStatus = 0 or micPass
1 or micFail
2 or micDone
3 or micWarning
Results can assume any status like Pass , Fail , Warning etc. You can also send
screenshot to the test results window.
40) How will you declare a variable in QTP ?
You declare using a DIM keyword. You assign value to the variable using the SET
keyword.
Ex.Dim temp 'Will declare the temp variable
Set temp = 20 ' Will assign a value 20 to temp.
41) What is GetRoProperty ?
GetRoProperty is a standard method provided by QTP to fetch property values of a run
-time object.
42) What is smart Identification?
Typically, if even one of the on-screen object property does not match the recorded
object property. The test fails.
In smart identification, QTP does not give an error if the property values do not match,
but uses Base filter and Optional Filter properties to uniquely identify an object. In
Smart identification, if a property value does not match the script does not fail but it
proceeds ahead to compare the next property. Smart identification can be enabled in
Object Identification Dialog box.
43) How would you export a Script from one PC to another in QTP ?
We can make use of the "Generate Script" function available in Object Identification,
Test Settings and Tools/Options tab to create a zip of the script at the source computer.
These zip files then can be imported into QTP at the destination computer.
44) Can launch two instances of QTP on the same machine ?
No. You can work with only single instance of QTP on the same machine. But QTP itself
can work on multiple instances of the Application Under Test (AUT). Ex: QTP can
handle multiple IE browser windows.
45) Give the syntax to import/export xls into QTP.

DataTable.ImportSheet "..\..\TestData\Input.xls",1,dtGlobalSheet
DataTable.ExportSheet "..\..\Results\Output.xls","Global"
47) What is the standard timing delay for web based application in QTP ?
The standard delay is 60 seconds. This is can be changed in Test Settigns.
48) What is the Action Conversion Tool ?
It is an in-built tool provided by QTP to convert Actions into Business Process
Components.
49) What is the extension for a function library ?
The extension is '.QFL'
50) If the Global Data sheet contains no data and the Local Datasheet contains two rows
of data, how many times will the test iterate?
The test will iterate only once - global iteration.
51) Explain how to read registry key in UFT ?
The example demonstrated here explains how to read registry key in UFT
Create a shell object
set MyShell= CreateObject (WScript.Shell)
Read the value of key from the registry
RegValue =MyShell.RegRead (varpathofkey)
in above function we have to pass the path of key in registery.
e.g. HKCU\software\ie\settings
msgbox RegValue
52) What are the ways in UFT to get system environment variables in UFT?
There are three ways to get system environment variables in UFT
Use the WSH shell object
Use WMIs Win32_Environment Class
Read variables from the registry
Set myShell = CreateObject (WScript.Shell)
WScript.Echo myShell.ExpandEnvironmentStrings( "%PATHEXT%" )
myShell=Nothing,
The output will be .BAT;.CMD;.VBS;. VBE;. JS;. JSE
Other user variable, like TEMP, overwrite their system counterpart
Set myShell = CreateObject( "WScript.Shell" )
WScript.Echo myShell.ExpandEnvironmentStrings( "TEMP=%TEMP%" )
myShell=Nothing
The output will be
TEMP:C:\DOCUME~1\You\LOCALS~1\Temp
53) Mention the steps required in UFT to send mail from outlook?
To send mail from outlook in UFT,
Set Outlook = CreateObject ("Outlook.Application")
Dim Message 'As Outlook.MailItem
Set Message = Outlook.CreateItem(olMailItem)
With Message
.Subject = Subject
.HTMLBody = TextBody
.Recipients.Add (aTo)
Const olOriginator = 0
.Send
End With

54) Explain how you can fetch data from database in UFT?
To fetch data from database in UFT, you have to follow the code below
Set db= createobject (ADODB.Connection)
db.Open Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=G:\guru99\vb6\admission_project.mdb;
Persist Security Info= False
Set rst=createobject(ADODB.Recordset)
rst.Open select*from Course, db, 3
id=rst. RecordCount
For i=0 to id-1
Print rst.field (0) & rst.fields (1) & rst.fields (2) & rst.fields (3)
rst.Movenext
Next
55) What are the codes we can use to get files from ftp server in UFT?
To get ftp files from ftp server, you have to use below code
a) put- To store single file on server
b) get- To download single file from ftp server
c)
mget- To download multiple files from server
d) mput- To store multiple files on server
e) delete- To delete files on ftp server
MyShell.Run "%comspec% /c FTP -n -s:" & commandstoworkwithftp & " " & Site, 0,True
56) In UFT how you can prevent the system from getting locked?
To prevent system getting locked, any of the two ways can be used
Create a simple vbs file having code to press numlock key and run that vbs file
Edit one registry key DisableLockWorkstation =1 to disable locking
57) What is descriptive programming in UFT means?
Descriptive programming includes property name and property value. Whenever UFT
is facing difficulty in identifying objects from object repository, and instead the object is
directly identified from the script is known as descriptive programming.
58) In UFT explain the difference between qfl and vbs files?
a) qfl is quick test function library file while vbs is Microsofts vbscript
b) qfl is a non-executable file while vbs is an executable file
c)
To use file in UFT associate qfl file from test setting, while to include vbs file use
execute file statement
59) What is the code to write data to text file in UFT?
To write data to text file in UFT code is
Content = Guru99 Rocks
Set Fo = createobject ("Scripting.FilesystemObject")
Set f = Fo.openTextFile ("c:\myFile.txt",8,true) ' open in write mode
f.Write (contents)
f.Close
Set f = nothing
60) How to write data to excel file in UFT?
Code to write data to excel file in UFT is
filepath = C:\Bugs\Reports.xlsx
Set objExcel = CreateObject(Excel.Application)
objExcel.Visible= True
Set Wb= objExcel.Workbooks.Open (filepath)
Wb.worksheets(1).Cells(1,1).Value = guru99 read value from Excel file

61) How to create TSR file in UFT?


TSR means Test Shared Repository, it is created to share object repository.
To create TSR file, follow the steps
Open object repository
Go to file menu
Go to export local objects option and select it
After that, UFT will ask you to store .tsr file. Give the path and save. This will create .tsr
file in UFT
62) How to connect to QC in UFT?
To connect with QC, UFT provides the option to connect QC directly from UFT GUI.
a) Go to file menu
b) Select (QC) quality center
c)
You will be asked to - Enter QC url
d) Enter user id, password and project
Following above steps will allow you to connect with QC, later on you can execute the
tests from QC itself.
64) When we should use descriptive programming in UFT ?
Either through object repository or description programming, UFT identifies objects.
Descriptive programming is used in following scenarios
a) It is used to remove duplicate objects. Same objects exists in different screens or
windows of your application. If you use OR in this case you have to store same object
under different object hierarchy in OR. To deal with such situation, descriptive
programming is used
b) It is not appropriate in certain scenarios to store the objects inside OR (Object
Repository). Suppose if you want to print 100 links on the page, you should not store all
links in OR. Instead you should use Description Programming to access those links.
65) What is settoproperty and when to use it in UFT?
Settoproperty stands for set test object property. You can use this property to change
the object values at runtime. You can edit the property values during the runtime, but
the changes that are made are temporary.
66) How to create an array of dictionary in UFT?
We can create an array of dictionary using syntax
Dim ArrayofDictionary(2)
First element of array
Set ArrayofDictionary(0)= createobject("scripting.dictionary")
ArrayofDictionary(0).Add "key1", "temp1"
ArrayofDictionary(0).Add "key2", "temp2"
Added keys in first dictionary
Second element of array as dictionary
Set ArrayofDictionary(1)= createobject("scripting.dictionary")
ArrayofDictionary(1).Add "key1", "temp1"
ArrayofDictionary(1).Add "key2", "temp2"
Added keys in second dictionary..and so on
67) What is the difference between Array and Dictionary?
Array
Dictionary
Dynamic array is possible
There is no concept of dynamic dictionary
Size of array must be set before the use of
The size of dictionary do not need to be
array
set
We have to use redim statement before
To add extra element there is no need to

adding extra element into dynamic array

write any statement. We just use add


method
There is no particular method to release the Element which is not required any longer
memory if particular element is not required can be removed from the dictionary
68) What is round function in UFT?
Round function in UFT is used to round the decimal
For example
Mydecimal = 6.3433333
Roundedvalue= Round(Mydecimal , 3)
Print roundedvalue, it will print 6.343
69) How to find the total number of rows in the webtable in UFT?
There are three ways which we can find the count of rows in the table in UFT
a) Using rowcount property of UFT webtable object
b) Using GetROProperty of UFT
c) Using HTML DOM + UFT
70) How to create excel file in UFT ?
steps will create excel file in UFT,
'Create a new Microsoft Excel object
Set myExcel = createobject("excel.application")
'To make Excel visible
myExcel.Application.Visible = true
myExcel.Workbooks.Add
MyExcel.worksheets(1).Cells(1,1). Value = Scenario Id
MyExcel.worksheets(1).Cells(1,2).Value = Scenario Name
MyExcel.worksheets(1).Columns(1).ColumnWidth = 10
MyExcel.worksheets(1).Columns(2).ColumnWidth = 40
MyExcel.worksheets(1).Columns(3).ColumnWidth = 20
MyExcel.worksheets(1).Columns(4).ColumnWidth = 20
MyExcel.SaveAs "c:\guru99.xlsx"
MyExcel.close
objExcel.Quit
blnFlag = False
72) Explain in what ways we can export datatable to excel in UFT?
To export data-table to excel, there are two methods.
a) DataTable.Export (C:\export.xls)
b) DataTable.ExportSheet C:\mysheet.xls ( If excel file does not exist, new file is
created)
73) In datatable sheet in UFT, how to read a value from the cell?
To read a value from the cell, we follow 2 step process
a) We set the row pointer in first step
b) In second step we define the parameter/column name from the sheet to read
Example:
For this example, we have set the row pointer to 2 in transaction sheet
Datatable.GetSheet(Transactions).SetCurrentRow(2)
Now, we have to specify that we want to read a value from the module_name column
from the transaction sheet
Print datatable.Value (Module_Name, Transactions)
73) What are the loops available in UFT and what they do?
There are 3 loops available in UFT

a) Do..Loop : Do Loop will run a block of statements repeatedly


b) For..Next : For Next Loop will execute a series of statements until a specific
counter value
c)
ForEach : In order to execute a series of statements for each statements for
each object in collection For Each Loop is used
While.Wend Loop : While Wend Loop is used to execute a series of statements as long
as given condition is true
74) What are the types of error need to be handle in UFT?
There are three types of error that one will face in UFT
a) Syntax Errors
b) Logical Errors
c)
Runtime Errors
75) What are the ways you can handle run time errors?
There are various ways to handle run time errors
a) Using test settings
b) Using on error statement
c)
Using err Object
d) Using Exit Statement
e) Recovery Scenarios
f)
Report Object
76) What is the difference between exitaction and exititeration?
Exitaction is used when we want to exit from a particular action, while exititeration is
used to exit from a particular action iteration of an action.
77) In QTP how you can remove the spaces from string?
You can use replace function to remove spaces from string in QTP
Print replace( sdsd sd sd s , ,)
Output will be sdsdsdsds
Itrim function can be used if only leading spaces from string needs to be removed
Print Itrim( sdsd sd s ) Output will be sdsd sd s
You can use rtrim function to remove trailing spaces from string
Print rtrim( sdsd sd s ) Output will be sdsd sd s
78) In QTP how you can get the last character from a string?
Code to get the last character of a string in QTP
print right( junior,1) Output will be r
79) How to add synchronisation points in QTP?
There are 4 ways through which we can add synchronisation points in QTP
a) Wait statement : This statement will pause the execution for x seconds until object
comes up
b) Wait property : This method will wait until property of object takes particular
value
c)
Exist statement : This statement will wait until object becomes available
d) Sync method: The code will wait until browser page is completely loaded. For web
application testing this method is used.
80) In QTP explain what is crypt object
Crypt object in QTP is used to encrypt a strings.
Syntax
Crypt.Encrypt(Guru99)
Example :
In this example, value in pwd variable is encrypted using the Crypt. Encrypt method.

Then this encrypted value is entered into editbox.


pwd= myvalue
pwd = Crypt.Encrypt (pwd)
Browser(myb).WinEdit (pwd). SetSecure pwd
81) Mention what is the difference between Excecute file and loadfunction library ?
In execute file, we cant debug the statements. With loadfunction library, statements
can be debug and can also load multiple library files.
82) Explain how you can find length of array in QTP?
The code to find the length of array in QTP is
print (ubound(arr)+1)
Ubound returns the last index in array- so length of array will be +1. This will be total
number of elements in array
85) What is Optional step in QTP ? How you can add optional step in QTP?
When running a test, it test fails in opening a dialog box, QTP does not necessarily abort
the test run. It bye passes any step designated optional and continues running the
test. By default QTP automatically marks as optional steps that open certain dialog
boxes. In order to set an optional step in the keyword, right click and select Optional
Step. The icon for optional step would be added in next step. In the expert view to add
optional step, add optional step to the beginning of the VBScript statement.
87) How you can write contexts to text file in QTP?
Content = Guru99
Set Fo = createobject(Scripting.FilesystemObject)
Set f =Fo.openTextFile(c:\abc.txt, 8,true)
f.Write (contents)
f.Close
Set f= nothing
88) When option explicit keyword is used in QTP?
To specify that all variable must be declared before use in QTP, Option Explicit
keyword is used.
89) In QTP how you can exit for loop?
You must use Exit For statement to exit for loop in QTP. Exit For statement will get
the control out of the for loop
For count= 1 to 3
TempNum= mid(Tempstr,count,1)
If isnumeric(TempNum) Then
LenghtNum = LengthNum & TempNum
Else
Exit For
End If
Next
GetStrLenNumber = LengthNum
91) In QTP, explain what is qrs file?
qrs means Quicktest Recovery Scenario. By using recovery scenario manager we can
handle exceptions in test execution.In QTP using recovery scenario manager we can
handle exceptions in test execution. In QTP when you create a recovery scenario, you
must save it in .qrs file. qrs file may have any number of scenarios defined in it.
92) What is the significance of action 0 in QTP?
Action 0 is created by default when you create a new test in QTP along with action 1.
To determine the sequence in which we call other act ions 1,2,3 etc. action 0 is used.

93) Explain how you can replace string in QTP?


To replace part of string in QTP we will use the code as shown below
Example,
Str = (Guru99)
Suppose if you want to replace 99 with 88 then the code will
print replace(str,99, 88) output will be Guru88
94) What are the various automation frameworks available in QTP?
Various types of automation frameworks available in QTP are
a) Linear Scripting
b) The Test Library Architecture Framework
c)
The Data Driven Testing Framework
d) The Keyword Driven or Table Driven Testing Framework
e) The Hybrid Test Automation Framework
95) What is Object Spy and what is the function of object spy in QTP?
Object Spy is a feature in QTP by using which you can view both the test and run time
object properties and methods.
96) What is GetROProperty and what are the steps involved in using GetROProperty?
GetROProperty is an in built method used to retrieve runtime value of an object
property.
To use GetRoProperty it involves four steps
a) Record the object on which you want to use the GetROProperty in Object
Repository
b) Identify the run time property for the recorded object which could be used
c)
To retrieve the identified run time property and store the value in a variable
d) Use this value for further deductions
97) Explain how you can find the absolute value of the number in QTP?
To find out the absolute value of a number a built in function in QTP is available
Example- a= -1
Print abs(a) output will be 1
This code will find the absolute value of a number
98) How you can check if parameter exists in Datatable?
To check whether if parameter exists in data table we will use the code
on error resume next
val=DataTable(ParamName, dtGlobalSheet)
if err.number<>0 then
Parameter does not exist
else
Parameter exists
end if
99) In QTP explain what is keyword driven automation framework?
In keyword driven automation framework, the focus is mainly on keywords/functions
and not the test data. It means the complete focus is on creating functions which maps
the functionality of the application.
101) Explain how you can delete excel file in QTP?
To delete excel file in QTP,
Set fo = createobject(Scripting.filesystemobject)
fo.deletefile(C:\xyz.xlsx)
Set fo=nothing
102) What factors affect bitmap checkpoints ?

Bitmap checkpoints are affected by screen resolution and image size.


103) What is Accessibility Checkpoint?
World Wide Web Consortium (W3C) came up with some instructions and guidelines for
Web-based technology and information systems to make it easy for the disabled to
access the web. For example the standards make it mandatory to have an 'alt text' for an
image. So a blind person who is accessing the website, will use text - to -speech
converters and atleast understand what the image is about if not see it. All these
standards are checked by Accessibility Checkpoints.
104) What is .net Spy ?
Introduction
During software development, a good debugger is invaluable. Likewise, when a runtime
exception occurs, .NET's exception information (in particular, the call stack) provides
invaluable help. However, sometimes you run into problems where something is not
right, and to narrow down the problem, you need to investigate some internal state and
data in the application. This is not always easy using the debugger, because there is
seldom a natural place to put a breakpoint. It becomes even harder when the
application is deployed; the only option is usually if you have left some code in the
application to dump the internal state and data in question.
The tool Managed Spy and the article about Windows Forms Spy (wfspy) got me hooked
on the idea, that it ought to be possible to use reflection to read out public and private
members in any running .NET application. The solution presented here does - unlike the
others - not stop at the selected control (window); it presents a browsable hierarchy of
fields and properties. And unlike Managed Spy, the objects do not have to be
serializable; the entire object browser is injected into the address space of the spied
application. On the other hand, this solution does not offer any trace features.
The Solution
The solution to the problem described above is implemented as a tool named .NET
Object Spy. The main window is small and simple, but easy to use:

Drag the crosshair to another window, and it will be framed, and the main properties
are displayed in the main window. Once released, you get this menu:

Select the first option, and the browser is displayed (running in the address space of the
selected application):

You may right-click on a node to bring up a context menu. This allows you to refresh the
node (including children).
The top line in the window shows the "path" to the currently selected object,
e.g. Controls[0].Size.Width. You can also type this in and go directly to the
corresponding node. You can even call parameterless methods using this,
e.g. Controls[0].GetHashCode() or FindForm().Location.X. The Copy button copies the
"path" to the clipboard. The is intended as a help to ObjectSpyEvaluator, which is
explained later.
The Implementation
The solution contains three assemblies, which are described in detail in the following
paragraphs:
InjectLib - A C++ library that wraps the code injection as a generic
method, Injector.InvokeRemote
ObjectSpy - A C# executable that contains the main window
ObjectSpyLib - A C# library that contains the browser, which is injected into the spied
application
InjectLib (InvokeRemote)
A spinoff from this solution is a generic method with this signature (C# syntax):
Copy Code
object Injector.InvokeRemote(IntPtr hWnd, string assemblyFile,
string typeName, string methodName, object[] args)

This wraps the injection process in a generic way that can be used for other purposes.
The hWnd parameter identifies the window (and thus the process) in which your code
should be injected. The assemblyFile specifies the code that should be
injected, typeName specifies a class in this assembly, and methodName specifies a static
method on this class. The method is called with the supplied arguments, and may
optionally have a return value.
There are different methods to inject code into another process (see the CodeProject
article Three Ways to Inject Your Code into Another Process). This solution is based on
the same approach that most other tools use, Windows hooks (see Using Hooks for
details on Windows Hooks). The steps performed by InvokeRemote are:
Create a Windows message hook, using the Win32 API function SetWindowsHookEx
Serialize the parameters to shared memory
Send a custom message to the hook, to request its service
The hook (i.e., code injected in the target process) now:
Deserializes the parameters from shared memory
Loads the requested assembly
Invokes the requested method with the specified parameters
Serializes any return value to shared memory
Remove the hook
Deserialize the return value from shared memory and return it to the caller
SetWindowsHookEx requires the address of the hook function. This must be exported
from the library, which cannot be done from C#. Therefore, this library is made as a
mixed-mode C++ library, using Visual Studio 2005's C++/CLI support. I.e., the library
contains both native and managed code.
The memory shared between the two processes is simply a data segment created in the
library, i.e., it has a fixed size. For this library, it means that the serialized version of the
parameters to InvokeRemote must fit within 2000 bytes (obviously, they must also be
serializable). The same limitations apply to the return value. An alternative approach
could be memory mapped files (see this article on the MSDN Library).
The hook function caused a couple of interesting problems:
Problem #1: To make a nice wrapping of the serialization/deserialization, the
parameters to the message hook are wrapped in a serializable RequestMessage class,
declared in the InjectLib library itself. Despite this, the deserialization in step 4a above
failed, complaining that it was unable to find the InjectLib library - obviously ignoring
that it was running it in this exact moment! Searching the Internet indicated that this
situation may occur if the library is loaded using LoadFrom. Although it is Windows
itself that loads the library when it is injected, the suggested solution solved the
problem: subscribe to the eventAppDomain.CurrentDomain.AssemblyResolve. This
event occurs when the CLR cannot find an assembly, and lets you return the assembly
yourself.
Problem #2: When the message hook tries to load the assembly specified in
the InvokeRemote call (step 4b above), it cannot find it. This is solved by
using Assembly.LoadFrom instead of Assembly.Load. The message hook appends the
path of InjectLib, assuming that the requested assembly is located in the same place.
Otherwise, the requested assembly would have to be placed in the GAC or in the spied
application's folder. A solution similar to problem #1 could probably also be used.
ObjectSpy
ObjectSpy is the executable that contains the main window. It is written in C#, and
makes several Win32 API calls to find window handles and extract information etc. (for

declaring API calls in C#, pinvoke.net is very useful). The implementation of the
crosshair approach is highly inspired by the WinSpy demo project in Robert
Kuster'sarticle about three ways to inject code into another process. Apart from these
API calls, the code is very straightforward, and ends calling
InjectLib's InvokeRemote method:
Copy Code
Injector.InvokeRemote(hWnd, "ObjectSpyLib.dll",
"Bds.ObjectSpy.ObjectSpyForm", "ShowBrowser", new object[] { hWnd });
ObjectSpyLib
This C# library contains the browser form which is injected in the spied application. The
entry point is the static method specified by ObjectSpy's parameters to InvokeRemote:
Copy Code
public static void ShowBrowser(IntPtr hWnd)
This method creates an instance of the form and calls its Show method. The window
handle is "converted" into aControl, using Control.FromHandle. The control forms the
root of the object hierarchy. From there, the rest is exercising the reflection namespace.
Below each node in the tree that represents a non-null object, public and private fields,
and properties of that object are added the first time the node is expanded (indexers
excluded, since they require parameters). Furthermore, if an object
implements IEnumerable, the enumerated objects are added. Whenever a node is
selected in the tree, the corresponding object is used as the SelectedObject for
the PropertyGrid control in the right side of the window.
One thing worth noting is that generic type names are mangled. For example, the
typename returned from the reflection classes for the generic List class is "List`1". The
number after the backtick indicates the number of type parameters. ObjectSpyLib
unmangles this in a recursive manner, and presents it in C# syntax (i.e., using less-than
and greater-than characters).
ObjectSpyEvaluator
In addition to the browser form, ObjectSpyLib also includes the
class ObjectSpyEvaluator with this static method:
Copy Code
public static string Evaluate(IntPtr hWnd, string expression)
The expression parameter is identical to the object "path" that can be entered in the
browser. The result of the expression is returned. When performing automated GUI
testing, this makes it very easy to write validation code. The validation code might e.g.
make a call like this to check the Text property of the root node in a TreeView:
Copy Code
string result = (string)Injector.InvokeRemote(hWnd, "ObjectSpyLib.dll",
"Bds.ObjectSpy.ObjectSpyEvaluator", "Evaluate",
new object[] { hWnd, "treeView.Nodes[0].Text" });
A sample application using the Evaluate method - ObjectSpyEE - is included in the
downloads:

Future Enhancements
I hope this tool is useful as it is (at least it was fun making it!). However, there are
several improvements that I would like to do when I have time:
Include static members
Find and include "root objects" from the application, if possible (i.e., not just objects
referred to by the selected control)
Stop expansion when "simple types" (Int32 etc.) are encountered
Display private properties + public and private fields in PropertyGrid (by
implementingICustomTypeDescriptor)
Display additional type information about objects (FullName of declared
type, FullName (+Name?) of actual type), possibly in PropertyGrid
Allow changing the value of "simple types" (Int32 etc.), also when not public properties,
and thus in parent's PropertyGrid
Abort fetching enumerated objects if huge number of objects (when it takes too long)
Show information about from which base class a property or field is inherited, possibly
in PropertyGrid
Option to only show fields, not properties, by default (to avoid possible side effects from
calling a getaccessor)
History
2007-02-23 (ObjectSpy 1.2.0)
Added ObjectSpyEvaluator, ObjectSpyEE and related functionality in the browser form.
2006-12-05 (ObjectSpy 1.1.0)
Members are no longer sorted using SortedList (by key), but by Sort method on
ordinary List(and implementation of IComparable on ObjectInfo). This solves the
problem with handling obfuscated names (like in .NET Reflector). Due to culture issues,
keys for different members were considered equal. See Microsft Forums and MSDN for
details.
Tree in browser window no longer hides selection when there is no focus.
Refresh option added in the browser context menu.
ObjectInfo has been split up into base and derived classes.
Slightly modified icon for browser window (to distinguish it from main window).

2006-11-21 (ObjectSpy 1.0.0)


License
This article, along with any associated source code and files, is licensed under The Code
Project Open License (CPOL)
105) What is Array in vbscript?
dle this situation.
Store all the names in different variables
Store all the names in an array
If we follow the first approach,then we will end up mapping each name to variables.This
method will be tedious and time consuming task. The second approach of using array is
best solution in such situation, where we create an array and store all the names in one
variable itself which will reduce the effort in mapping each name with each variable.
Array is collection of objects/values in a systematic order.
In VBScript ,we can define arrays in two ways:
Static Array: It refers to the constant size list in which we cannot add element over its
defined capacity.
Dynamic Array: Refers to the variable size list in which elements can be added or
removed at run time.
For Static Array ,the format of declaring the variable is as below :

1 Dim ArrName(ArrSize)
where
ArrName=Array Name
ArrSize =Array Size
While defining the dynamic array ,we dont need to declare the size of array.

1 Dim ArrName()
where
ArrName=Name of an array
Assigning value to static array in VBScript
The values that needs to be assigned to the array needs to be on the right hand side of
the line

1 ArrName(ArrIndex)=Value
where
ArrName=Nameofanarray

ArrIndex:Location where value needs to be stored.


This needs to be an integer value starting from 0 (zero).
Assigning value to dynamic array in VBScript
In dynamic array we use the keyword Redim for redefining the size of an array. As we
have seen in Declaring an array, dynamic array doesnt have any size in starting. So we
can use Redim for defining the same.

1 Redim ArrName(ArrSize)
where
ArrName=Nameofanarray
ArrSize =Size of the array
Now, lets take an example, where we have 5 elements (10,20,30,40,50).We need to
assign these variables to an array in VB Script.
First we need to declare a dynamic array in VbScript for the same.

1 Dim Arr()
Now we need to increase the size of this empty array which can be done using Redim
keyword

1 Redim Arr(5)
As we have increased the size of the array as per our requirement,we will now assign
the value to this array starting from the position zero(0)

1 Arr(0)="10"
2.
3.
4.
5 Arr(4)="50"
So the overall code which has been designed till now looks like

1 Dim Arr

2 Redim Arr(5)
3 Arr(0)="10"
4 Arr(1)="20"
5 Arr(2)="30"
6 Arr(3)="40"
7 Arr(4)="50"
Lets see the value in the msgbox of the above code till now

1 For i= 0 to 4
2 FirstArr=FirstArr+"Arr("+cstr(i)+") : "+(Arr(i))&amp;vbnewline
3 next
4 msgbox FirstArr
The output will be as follows

1 Arr(0) : 10
2 Arr(1) : 20
3 Arr(2) : 30
4 Arr(3) : 40
5 Arr(4) : 50
Now if we want to add a new element say 60, so again we will redefine the size of array
to 6

1 ReDim Arr(5)
2 Arr(5)=60
Now if we check the output again of the array using the code

1 For i= 0 to 5
2 SecondArr=SecondArr+"Arr("+cstr(i)+") : "+(Arr(i))&amp;vbnewline
3 next
4 msgbox SecondArr
The output will be as follows

1 Arr(0) :
2 Arr(1) :
3 Arr(2) :
4 Arr(3) :
5 Arr(4) :
6 Arr(5): 60
We see that when we have added an element to an array in Vbscript using Redim
keyword,it makes Arr as blank for index 0 to 4.
If we want to preserve the values of an array as it is ,we can achieve the same using
the Preservekeyword.

1 Redim Preserve ArrName(ArrSize)


where
ArrName=Array Name
Arrsize=Size of an array
So ,now the code will be as below

1 Dim Arr
2 Redim Arr(5)
3 Arr(0)="10"
4 Arr(1)="20"
5 Arr(2)="30"
6 Arr(3)="40"
7 Arr(4)="50"
8 Redim Preserve Arr(5)
9 For i= 0 to 5
10 SecondArr=SecondArr+"Arr("+cstr(i)+") : "+(Arr(i))&amp;vbnewline
11 next
12 msgbox SecondArr
The output will be as follows

Arr(0) :10
Arr(1) :20
Arr(2) :30

Arr(3) :40
Arr(4) :50
Arr(5): 60
In this way we can assign the values to the dynamic array.
PS: While using array in Vbscript, we recommended the usage of dynamic array instead
of the static array as it helps to reduce the memory consumption during execution.
108) what is error handling in qtp?
Error handling is the way for responding to occurrence of some unexpected situation
that arrives during the computation. In automation testing, these unexpected situation
can be like objects of application getting changed or some mathematical manipulation
etc.
For handling such situation Visual Basic Script Edition (VBScript) provides us some of
the methods. The details and usage of these methods are as follows:
On error resume next
This statement specifies that when any run time error occurs at particular line in script
the control goes to the next line following the statement where the error as occurred.
For example: We are performing a division by zero, and if such situation occurs we dont
want script to be interrupted. So we will be adding On error resume next statement at
the top of the script.
On error resume next
Division=100/0
If Div=0 then
Msgbox Pass
Else
Msgbox Fail
End if
On error go to 0
Disables any enabled error handler and reset it to nothing
Err object
Err object is the intrinsic object with global scope means there is no need to create the
instance of it for accessing the various methods of it.The details of all the methods of
err object can be find in the below table:
Err Properties
Details
Number

Returns the integer value telling the type


of the error occurred

Description

Gives the reason for the occurrence of the


error

Source
HelpFile
HelpContext
Err Methos

Details

Clear

Helps to reset the error handler to nothing


once the error has been handled.

Raise

Lets take the example of division by zero again.


'Call the division function
call division
Function division()
on error resume next
'divide by zero
z=100/0
' Report the error occured. You can see the error number and description in msgbox
If Err.number <> 0 then
Msgbox Error Number + Err.Number
Msgbox Error Description + Err.Description
'disables error handling
on error goto 0
End if
End function
In Visual Basic, we have two more methods available for error handling
On Error Goto Line Moves the control to a particular line number.
On Error Goto Label Moves the control to a particular section of code which is defined
in a label.
These two methods are not available in VBScript.
109) What is Virtual Objects?
When Nothing Works Virtual Objects is the weapon to achieve your goal. Many of the
times you will find that QTP is not able to recognize an object, even if the object behaves
like a standard object. Virtual objects helps in such situation, to be able to identify and
run tests.
Virtual object feature in QTP enables us to create and run tests on objects that are not
normally recognized by QTP. we can define such objects as virtual objects and map
them to standard classes like button, checkbox etc.QuickTest emulates the actions on
virtual object during the run session. A virtual object can be defined using the virtual
Object Wizard. The wizard prompts you to select the standard object class to which you
want to map the virtual object. You then mark the boundaries of the virtual object using
a crosshairs pointer. Next, you select a test object as the parent of the virtual object.
Finally, you specify a name and a collection for the virtual object. A virtual object
collection is a group of virtual objects that is stored in the Virtual Object Manager under
a descriptive name. Virrtual Object Manager feature enables us to create and manage
virtual objects.
Virtual Object Wizard
Launch Virtual Object Wizard by selecting Tools > Virtual Objects > New Virtual Object
Select Next at Welcome screen

figure 1 : Virtual Object Wizard Welcome screen


Select the class which most resembles your virtual object.

figure 2 : Map to a Standard Class


Click on Mark object button and mark the area in application (around the object you
want to create virtual)
Click Next

figure 3 : Mark Virtual Object


Select one of the following options
Entire Parent hierarchy if you want to add the whole hierarchy.
Parent only if you want to add only the parent.
Click Next

figure 4 : Object Configuration


Specify the desired object name and the collection name.
Click Finish.

figure 5 : Save Virtual Object


Virtual Object Manager
Select Tools > Virtual Objects > Virtual Object Manager to open Virtual Object
Manager.Virtual object manager list all of available virtual object collections. We can
delete the virtual object from virtual object collections.

figure 6 : Virtual Object Manager

To disable recognition of virtual objects while recording select Tools > Options and click
General tab, and select the Disable recognition of virtual objects while
recording check box.
Object Spy cannot be used on virtual objects
Scroll bars and Labels cannot be treated as Virtual objects
QTP does not support virtual objects for analog or low level recording.
If you have used virtual objects and that too only after doing a record, and you are
wondering if we have descriptive programming for virtual objects as well!
The answer to these is Yes, we do have and we can easily do the same for Virtual
Objects. For those who are not aware of what Virtual Objects are, let us first understand
what it is and how it works. Virtual object feature in QTP enables us to create and run
tests on objects that are not normally recognized by QTP. These objects can be any
object that behave like standard objects but are not recognized by QTP. Virtual objects
helps a lot in such situations.
Recently, I encountered a similar situation where I had to click on a link which was
there in the email body (I will elaborate the whole scenario in a seperate post).
Although the link was behaving properly it was not getting recognized by QTP, actually
QTP was identifying the whole body section as an object. objective was to open the url
which was associated with the link and that was getting opened only after clicking the
link at the email body. I tried other means but no luck. So finally in this situation Virtual
Object was very helpful and it worked like a charm.
So, we can define such objects as virtual objects and map them to standard classes like
button, checkbox etc. QuickTest emulates the actions on virtual object during the run
session. A virtual object can be defined using the virtual Object Wizard(Tools>Virtual
Objects>New Virtual Object). The wizard prompts you to select the standard object
class to which you want to map the virtual object. You then mark the boundaries of the
virtual object using a cross-hair pointer. Next, you select a test object as the parent of
the virtual object. Finally, you specify a name and a collection for the virtual object. A
virtual object collection is a group of virtual objects that is stored in the Virtual Object
Manager under a descriptive name. Find more details on virtual objects step by step with
screenshots in my earlier post Virtual Objects When Nothing works.
The virtual objects that you create using the virtual object wizard, gets stored as VOT
file into <QuickTest installation folder>\ dat \ VoTemplate. That means, if you want to
use the script in which you have added the virtual object onto some other machine then
this VOT file also needs to be copied to the same location on the other machines
wherever you want the script to execute. This is main challenge for maintaining the
script and the execution on multiple machines or in other terms portability. To
overcome this issue, Descriptive programming is the best way. Basically a virtual object
stores and uses the properties x,y,width and height with it. so if by any means we are
able to maintain these properties and values then we are done. below is an example of
how we can do it

1 Browser("Google").Page("Google").VirtualButton("x:=667","y:=158","height:=21","wid
th:=75","name:=Saket").Click

This way we can run the script without having the virtual object collection or the VOT
files on the machine.We can do the same with using description object as well.

Set oVDesc=Description.Create
1
oVDesc("x").value=667
2
oVDesc("y").value=158
3
oVDesc("height").value=18
4
oVDesc("width").value=41
5
Browser("name:=Google").Page("title:=Google").VirtualButton(oVDesc).click
Descriptive programming for virtual objects can be done only for the classes which can be
created using the virtual object manager.
for virtual lists objects use one more property rows:=row number
for tables use rows:=row number and columns:=column number
110) What is Dictionary object ?
Most of the time; We use variables, when we need to store a input value or a value
retrieved from an outside source. When there are many such values, either we use
individual variables or we can store in an array. Alternatively, information can also
be stored in a Dictionary object. It is a part of VB Script and so it can be used with the
tools supporting VBS.
The Dictionary object is used to hold a set of data values in the form of (key, item) pairs.
A dictionary is sometimes called an associative array because it associates a key with an
item. The keys behave in a way similar to indices in an array, except that array indices
are numeric and keys are arbitrary strings. Each key in a single Dictionary object must
be unique.
A Dictionary object can contain any data including objects and other Dictionary objects.
The value of these dictionary items can be accessed by using unique keys that are stored
along with the data, rather than by using an items ordinal position as you do with an
array. This makes the Dictionary object ideal when you need to access data that is
associated with a unique named value.
Adding Keys and Items
Dictionary is a COM objects, it can be instantiated in the same way as
any other COM Object. TheProgID for a Dictionary object is Scripting.Dictionary, and so
the following example creates a Dictionary object using CreateObject:

1 Dim oDict
2 Set oDict = CreateObject("Scripting.Dictionary")
One you have created an instance of the Dictionary object, you can use
the Add method to add items to the dictionary. The Add method requires two
parameters, which must be supplied in the following order and separated by a comma.
for example

Key

Value

Book1

QTP Unplugged

Book2

QTP DP Unplugged

Book3
UFT & QTP Interview Unplugged
Dictionary keys must be unique. In the examples below, after the first line is interpreted,
the key Book1 will already be in the Dictionary.

1 Set oDict = CreateObject("Scripting.Dictionary")


2 oDict.Add "Book1", "QTP Unplugged"
3 oDict.Add "Book2", "QTP DP Unplugged"
4 oDict.Add "Book3", "UFT & QTP Interview Unplugged"
To retrieve the value from dictionary created, we can use .item method of dictionary
object.

1 oDict.item("Book2")
One potential problem in using the Dictionary object is that any attempt to reference
an element that is not contained in the Dictionary does not result in an error. Instead,
the non-existent element is added to the Dictionary. Consider the following script
sample, which creates a Dictionary, adds three key-item pairs to the Dictionary, and
then attempts to echo the value of a non-existent item, Book4:

1 Set oDict = CreateObject("Scripting.Dictionary")


2 oDict.Add "Book1", "QTP Unplugged"
3 oDict.Add "Book2", "QTP DP Unplugged"
4 oDict.Add "Book3", "UFT & QTP Interview Unplugged"
5 MsgBox oDict.Item("Book4")
When the script tries to output the value of the nonexistent item, no run-time error
occurs. Instead, the new key, Book4, is added to the Dictionary, along with the item
value Null.
To avoid this problem, check for the existence of a key before trying to access the value
of the item. you can do so using .exists method.

1 Set oDict = CreateObject("Scripting.Dictionary")


2 oDict.Add "Book1", "QTP Unplugged"
3 oDict.Add "Book2", "QTP DP Unplugged"
4 oDict.Add "Book3", "UFT & QTP Interview Unplugged"
5 if oDict.Exists("Book4") then msgbox oDict.Item("Book4")
Looping through the Items in Dictionary Object
Each item stored in a Dictionary object can be accessed by using For Each statements as
shown in the snippet below

1 Dim oItem
2 Dim sItem, sMsg
3 Dim oDict
4
5 Set oDict = CreateObject("Scripting.Dictionary")
6
7 Set oDict = CreateObject("Scripting.Dictionary")
8 oDict.Add "Book1", "QTP Unplugged"
9 oDict.Add "Book2", "QTP DP Unplugged"
10 oDict.Add "Book3", "UFT & QTP Interview Unplugged"
11
12 For Each oItem In oDict
13 sItem = oDict.Item(oItem )
14 sMsg = sMsg & sItem & vbCrLf
15 Next
16
17 MsgBox sMsg
Configuring Dictionary Properties
The Dictionary object has only one configurable property, Compare Mode, which plays
an important role in determining which keys can be added and which ones cannot.
By default, a Dictionary is created in binary mode, which means each key in the
Dictionary is based on its ASCII value. This is important because the ASCII value of an
uppercase letter is different from the ASCII value of that same lowercase letter. In
binary mode, both of these services can be added to the Dictionary as individual keys. So
we can have same keys for multiple Items when in binary mode. for example, book and
BOOK
When a Dictionary is configured in text mode, uppercase and lowercase letters are
treated identically.
To configure the Dictionary mode, create an instance of the Dictionary object and then
set the CompareMode property to one of the following values:

0 Sets the mode to binary. This is the default value.


1 Sets the mode to text.

1 Set oDict = CreateObject("Scripting.Dictionary")


2 oDict.CompareMode = 1
You cannot change the CompareMode property of a Dictionary if that Dictionary
contains any elements. This is because the binary mode allows you to differentiate
between keys based solely on uppercase and lowercase letters. In text mode, however,
these three keys are considered identical. If you had these elements in a binary
Dictionary and were able to reconfigure that Dictionary in text mode, the Dictionary
would suddenly contain three duplicate keys, and it would fail. If you must reconfigure
the Dictionary mode, you first need to remove all items from the Dictionary.
Manipulating Keys and Items in a Dictionary
By itself, a Dictionary is of little use; a Dictionary is valuable only when you can
access, enumerate, and modify the keys and items within that Dictionary. After you have
created a Dictionary, you will probably want to do such things as:
Determine how many key-item pairs are in that Dictionary.
Enumerate the keys and/or items within the Dictionary.
Determine whether or not a specific key exists in the Dictionary.
Modify the value of a key or an item in the Dictionary.
Remove key-item pairs from the Dictionary.
To remove a value from a dictionary, use the .Remove method and specify the key to
remove. For example:
oDict.Remove Book2
To remove all values and clear the dictionary, use the .RemoveAll method. Use
the .Count property to obtain a count of values in the dictionary.
The .Keys and .Items methods return an array containing all the keys or items from the
dictionary. For example:

1 aBooks = oDict.Keys
2 aNames = oDict.Items
Enumerating a Dictionary
Items and Keys method returns the array of Items and keys respectively. These methods
cannot be directly used to access the values, there return array has to be first assigned
to a variable and then accessed. Below example illustrates the enumerations.

1 'Create the dictionary object


2 Set oDict = CreateObject("Scripting.Dictionary")
3 oDict.Add "Book1", "QTP Unplugged"
4 oDict.Add "Book2", "QTP DP Unplugged"
5 oDict.Add "Book3", "UFT &amp; QTP Interview Unplugged"
6
7 aItems = oDict.Items
8
9 'Print all the items in the dictionary
10 For i = LBound(aItems) To UBound(aItems)
11 Print aItems(i)
12 Next
13
14 'Print all keys in the dictionary
15 'We can use For each loop also to access the array
16 aKeys = oDict.Keys
17 For Each Key in aKeys
18 Print "Key - " &amp; Key
19 Print "Value - " &amp; oDict(Key)
20 Next
Use of Dictionary Objects
Generally dictionaries are used when items need to be stored and recovered by name.
For example, a dictionary can hold all the environment variables defined by the system
or you have some configuration values for the script which you want to be accessed
through out your script scope.
Here is nice
A very simple answer for when should we use dictionary object? would be use
dictionary object, when you need find value by key
As Reserved Object in QTP/UFT
You can add dictionary as a reserved object in QTP/UFT , follow the steps below
Open registry editor through windows run window (type regedit)
Browse to HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest
Professional\MicTest\ReservedObjects
Create a new key under this key with Name as Dictionary and as String value ProgID
with data as Scripting.Dictionary as shown in below snapshot.

Start QTP, type Dictionary., it should show the methods and properties of dictionary
objects to use.

Sorting a Dictionary
Below function demonstrate, how we can sort a dictionary with items. [Source]

1 Const dictKey = 1
2 Const dictItem = 2
3
4 Function SortDictionary(objDict,intSort)
5 ' declare our variables
6 Dim strDict()
7 Dim objKey
8 Dim strKey,strItem
9 Dim X,Y,Z
1
0 ' get the dictionary count
1 Z = objDict.Count
1
1 ' we need more than one item to warrant sorting
2 If Z &gt; 1 Then
1
' create an array to store dictionary information
3
ReDim strDict(Z,2)
1
X=0
4
' populate the string array
1
For Each objKey In objDict
5
strDict(X,dictKey) = CStr(objKey)
1
strDict(X,dictItem) = CStr(objDict(objKey))
6
X=X+1
1
Next
7
1
' perform a a shell sort of the string array
8
For X = 0 to (Z - 2)
1
For Y = X to (Z - 1)
9
If StrComp(strDict(X,intSort),strDict(Y,intSort),vbTextCompare) &gt; 0 Then
2
strKey = strDict(X,dictKey)
0
strItem = strDict(X,dictItem)

2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4

strDict(X,dictKey) = strDict(Y,dictKey)
strDict(X,dictItem) = strDict(Y,dictItem)
strDict(Y,dictKey) = strKey
strDict(Y,dictItem) = strItem
End If
Next
Next
' erase the contents of the dictionary object
objDict.RemoveAll
' repopulate the dictionary with the sorted information
For X = 0 to (Z - 1)
objDict.Add strDict(X,dictKey), strDict(X,dictItem)
Next
End If
End Function
111) What are Object models in qtp ?
An Object Model is basically the way we use the object properties in a Programming
language or technology. When we say usage of object properties, it means accessing
the objects by object references to achieve the objectives like invoking a particular
method of object. For example, object model of MS Excel, which enables other
program to control it via different methods and properties.
A collection of objects or classes through which a program can examine and manipulate
some specific parts of its world. In otherwords, the object-oriented interface to
someservice or system. Such an interface is said to be the object model of the
represented service or system.
In this post we will discuss about the four different types of Object Models
Test Object Model ( TOM )
Document Object Model ( DOM )
Component Object Model ( COM )
Automation Object Model ( AOM )
Test Object Model ( TOM )
A collection of object types or classes which represents the different objects in the
application. For Example a button object or edit box object in an application are the
objects of and represent Button class or Edit box class. These test object class has a
several properties to uniquely identify the objects of the particular class and methods
to perform specific actions.
There are two types of objects in TOM,
Test Object and
Run-time object.
The objects which QuickTest creates and stores to represent the object in application,
is a test object whereas a run-time object is the actual object in the application on
which methods are performed during the run session, i.e the test object object

5
4
6
4
7
4
8
4
9
5
0

properties are the properties as they are saved in the test object repository. Run time
properties refers to the object properties as it appears in the application under test.
for example, a button with one of the properties enable

is true in the object


repository, which can be enable/disable at run time depending on certain conditions.
with this we can understand that the test object properties does not require your
application to open and can be modified whereas a run-time
run time object property requires
the application to be open and it cannot be modified.
If you have ever wondered about the RO in GetROProperty and TO in SetTOProperty
SetTOProperty,
now you know that RO
O is for Run-time
Run
Object and so GetROProperty is used to
retrieve the value of the object at run time. TO is for Test Object and so the value of
an object in object repository can be modified usingSetTOProperty.
using
Document Object Model ( DOM )
Web Pages aree organized into different objects like document, tables etc using the
properties and methods available for the objects. These objects can be accessed by
using scripts for the web pages. The Document Object Model is an interface(API)
which allow programs and scripts to access and update the content,, structure and
style of documents. This is not only applicable for web pages (HTML) but for XML as
well.
The objects in the document are in a hierarchy. DOM helps QTP to access
access this
hierarchy of a web pagedirectly
directly by scripting. To access the DOM we use .
.object
method for the specific web object.
For example, you can use DOM to identify an object when QTP is not able to identify
an object. Consider the part of page source below for Google search page.

<div id=gbqfbwa class=jsb>


b>
<button id=gbqfba aria-label="Google
label="Google Search" name=btnK class=gbqfba><span
1 id=gbqfsa>Google Search</span></button>
2 <button id=gbqfbb aria-label="I'm
label="I'm Feeling Lucky" name=btnI class=gbqfba
3 onclick="if(this.form.q.value)this.checked=1;else
window.top.location='/doodles/'"><span
on='/doodles/'"><span id=gbqfsb>I'm Feeling
Lucky</span></button></div>
the part of the source is for the two buttons at Google search page.

If you need to click on the Google Search button using DOM, you will have to look into
the source. For the button there are certain properties like id, name etc, you can find
in the source above. These properties can be used to identify the object and do the
action. If we take the Name property, this can be used byGetElementsbyName
byGetElementsbyName method
as below

Browser("Google").Page("Google").object.getElementsByName("btnK").Item(0).cli
ck
You can use GetElementsbyTagName to have all the button objects and then search
for the required one as below
1

1 Set PageObject = Browser("Google").Page("Google").object


2 set ButtonObjects=PageObject.getElementsByTagName("button")
3
4 For each button in ButtonObjects
5
6
If lcase(button.type)="button" Or lcase(button.type)="submit" Then
7
If UCase(button.name)="BTNK" Then
8
button.click
9
Exit For
10
End if
11
End If
12 Next
I am listing here some important properties and methods that you can use in QTP
GetElementById Method returns a list of objects with specified id. If the id for the
objects are not unique it take the first object with the specified value of the ID
attribute.

1
2
3
4
5
6
7
8
9
1
0

Set PageObject = Browser("Google").Page("Google").object


Set InputObjects = PageObject.getElementsByTagName("INPUT")
inCount=InputObjects.Length-1
For i=0 to inCount
If InputObjects(i).Name="q" and InputObjects(i).Type="text" Then
PageObject.getElementsByName(InputObjects(i).Name)(0).Value="Automate
d-360"
Exit For
End If
Next

ElementFromPoint Method returns the object at specific coordinate on the page. for
example the below code finds the search text box as per x and y coordinate and sets
the value.

x=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROPro
perty("x")
1
y=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROPro
2
perty("y")
3
Browser("name:=Google").Page("title:=Google").Object.elementFromPoint(x,y).Val
ue="Automated-360"
Some useful Properties which can be used for different purposes
activeElement Retrieves the object that has the focus when the parent document
has focus. Get the name of the text box which has the focus during runtime

1 Print Browser("Google").Page("Google").Object.activeElement.name
cookie Sets or retrieves the string value of a cookie. Find more details on Cookie
here

1 Print Browser("Google").Page("Google").Object.Cookie
documentElement - Retrieves the root node of the document.

1 Print Browser("Google").Page("Google").Object.documentElement.innerHTML
readyState - Retrieves a value that indicates the current state of the object. This
property can be used for sync in QTP scripts.

1 Browser("Google").Page("Google").Object.readyState

Component Object Model ( COM )


It is used to enable interprocess communication and dynamic object creation in a large

range of programming languages. COM is the basis for several other Microsoft
technologies and frameworks, including OLE, OLE Automation, ActiveX, COM+, DCOM,
the Windows shell, DirectX, and Windows Runtime.
COM is basically used by developers to make the things simpler and easier to build
and link by creating reusable components. The objects can be accessed by the
interface (properties and methods) provided by COM for a particular class. Basically
the properties and methods of an object can be the interface of the object and
accessed by taking the reference of the object.
COM objects can be used with any tool that supports COM automation. And
since VBScript supports COM automation, It becomes very easy to use in QTP
scripting. But we cannot use all the COM objects, we can use only those objects that
expose a string called a programmatic identifier (ProgID). Although not all COM
objects have a ProgID, all COM objects have a 128-bit number called a class
identifier, or CLSID. If a COM object has a ProgID, you can use VBScript to instantiate
the object, invoke its methods and properties, and destroy the object.
To use a COM object in a script, you must first create an instance of the object. You
can do this by calling the CreateObject or GetObject method.

1 Set oFSO = CreateObject("Scripting.FileSystemObject")


CreateObject creates an Automation object of the specified class. If the application is
already running, it creates a new instance. Set statement creates the reference
between the object variable and the object. once the work is done the object
reference should be destroyed as below

1 Set oFSO = Nothing


You can also use GetObject method which returns a reference to an instance of an
object. It can be used in two way with its parameters, the objects pathname and the
objects ProgID.

1 Set oWord = GetObject("C:\Test\Test1.doc")


or

1 Set oWord = GetObject("","Word.Application")

Automation Object Model ( AOM )


An Object Model is a structural representation of objects that comprise the
implementation of a system or application. Automation enables software packages to
expose their unique features to scripting tools and other applications. Usually
Automation uses the Component Object Model (COM). A critical aspect of COM is, how
client and servers interact. A COM server is any object that provides services to
clients; these services are in the form of COM interface implementations like
Properties, Methods, Events and their relationships. Which can be called by any client
that is able to get a pointer to one of the interfaces on the server object.
QuickTest Professional is also a COM Server and its different methods and properties
are exposed by its COM interface which can be accessed by other applications and
scripting tools to control it from outside. In this post, we will see how to interact with
QTP from outside via Automation Object Model.
Find more detail in the post Automation Object Model : QuickTest Professional . It is
same for UFT as well without any changes. Below code snippet illustrates the launch
of UFT.

1 Dim UFTApp
2
3 Set UFTApp= CreateObject("QuickTest.Application") ' Create the application object
4
5 UFTApp.Launch 'Start QuickTest
6
7 UFTApp.Visible = True ' Make it visible
112) How To generate Random strings in QTP/UFT?
'************************************
'Logic Explanation:
'************************************
' RandomNumber ststement only gives specific random numbers between given
range
' 97-122 are the ASCII codes for a-z alphabets.
' Chr(97) will return 'a', Similarly Chr function return chacters based on ASCII codes
' In below function the random numbers will be generated between 97-122
' Using Chr function the generated numbers will be converted in to characters
' The generated characters will store in "gChr" variable
' Finally gChr value will be returned as Function Value
'************************************
Function GenerateRandomString(StrLength)
' Declare Variables
Dim StrLenIndex
Dim chrAscCode
Dim gChr
'Use for loop to generate StrLength many characters

For StrLenIndex = 1 To StrLength


' Get Random ASCII Code
chrAscCode=RandomNumber(97,122)
' Convert ASCII code in to character
gChr=gChr&Chr(chrAscCode)
Next
'Return converted character to function
GenerateRandomString=gChr
End Function
'************************************
'Function Calling
'************************************
MsgBox GenerateRandomString(5)
'************************************
113) Closing of Browsers all browsers Except Qc/ALM Except Last Browser Except
First Browser?
'##################################
'Close All browsers
'##################################
'Method 1
'***************************************************
'Call Function
Call CloseAllBrowsers("IE")
'***************************************************
'Logic Explanation
'SystemUtil.Closeprocessbyname closes specific process by name
Function CloseAllBrowsers(oBrName)
' Close the specific/all browsers
Select Case ucase(oBrName)
Case "IE"
'Close IE
SystemUtil.CloseProcessByName "iexplore.exe"
Case "FF"
'Close FF
SystemUtil.CloseProcessByName "firefox.exe"
Case "CHROME"
'Close CHROME
SystemUtil.CloseProcessByName "chrome.exe"
Case "ALL"
'Close All Browsers
SystemUtil.CloseProcessByName "iexplore.exe"
SystemUtil.CloseProcessByName "firefox.exe"
SystemUtil.CloseProcessByName "chrome.exe"
End Select

End Function
'***************************************************
'Method 2
'***************************************************
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "0" to Count-1 because the Object Indexing starts from "0"
'We will close each and every browser with for loop and index
Function CloseAllBrowsers()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim objIndex
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because Object Indexing starts from "0"
For objIndex=0 to oBrObjList.count-1
'Close the Browser
oBrObjList(objIndex).close
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except Alm/Qc
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We will check the the title before closing every browser with for loop and index

'We for loop from "0" to Count-1 because the Object Indexing starts from "0"
'If title is "Quality Center" or "ALM" we will not close it
Function CloseAllBrowsersExceptQC()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim objIndex
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because Object Indexing starts from "0"
For objIndex=0 to oBrObjList.count-1
'Verify the name of the browser is "Quality Center" or "ALM"
If lcase(oBrObjList(objIndex).GetROproperty("name"))<>"mercury quality center"
then
'Close the Browser
oBrObjList(objIndex).close
Exit For
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except last opened browser
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "1" to Count-1 because the in this script we will not work with
object indexing
'We will get the count of number of browsers and write a FOR loop with Count-1
times
'because we should close all browsers except one
'Each time we have to verify "0" creationtime browser exist and if exist close it
'We will repeat this Count-1 times
'The For Loop gets exit when the last browser creationtime becomes "0"

Function CloseAllBrowsersExceptLastBrowser()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim iCounter
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because we should close all browsers except one
For iCounter=1 to oBrObjList.count-1
'Close the first browser each time by checking creationtime "0"
If Browser("creationtime:=0").Exist Then
'Close Browser
oBrObjList("creationtime:=0").close
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except First opened browser
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "1" to Count-1 because the in this script we will not work with
object indexing
'We will get the count of number of browsers and write a FOR loop with Count-1
times
'because we should close all browsers except one
'Each time we have to verify "1" creationtime browser exist and if exist close it
'We will repeat this Count-1 times
'The For Loop gets exit when there no extra browsers
Function CloseAllBrowsersExceptLastBrowser()

'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim iCounter
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
' Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because we should close all browsers except one
For iCounter=1 to oBrObjList.count-1
'Close the second browser each time by checking creationtime "1"
If Browser("creationtime:=1").Exist Then
'Close Browser
oBrObjList("creationtime:=1").close
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
114) Prepare QTP/UFT for Test Batch Execution Using AOM?
'***************************************************
'***************************************************
'Author - QtpSudhakar.com
'Purpose - To Run a Test Batch for all tests in side of a folder
' - This will create a CSV file which will have all the status of execution
'How to Use - Specify the Folder Path of where tests are stored
' - Make sure you don't have any other empty folders without QTP test
' - Give TestPath, Save the code into VBS file and Double click on vbs file
'***************************************************
'For any doubts contact https://www.facebook.com/Qtpsudhakarblog
'***************************************************
'***************************************************
'Declare Variables
Dim TestsFolderPath 'To specify Tests folder path
Dim QtApp 'To store Qtp Automation Object
Dim fso 'To access file system
Dim fld 'To store the test folder object
Dim tFlName 'Unique File name to store Test Results
Dim fl 'To store Result File Object
Dim fldLst 'To store Child Folders(tests) of base folder
Dim f 'To store each QTP Test Folder

Dim tPath 'To store QTP Test Path


Dim tName 'To Store QTP Test Name
Dim WSH 'To open the created CSV result file
'Specify Base Tests Folder Path
TestsFolderPath="C:\Users\sudhakar\Desktop\tests"
'Create QTP Automation Object
Set QtApp = CreateObject("QuickTest.Application")
QtApp.launch 'open QTP
QtApp.visible=True 'Make it visible
'Create File system object
Set fso = CreateObject("scripting.filesystemobject")
'Get the base Tests folder
Set fld=fso.GetFolder(TestsFolderPath)
'Generate a unique file name with date and time
tFlName="TestExecution_"&Replace(replace(replace(now,"/","_"),":","_")," ","_")&".csv"
'Create the CSV file with the created name
Set fl=fld.CreateTextFile(tFlName)
'Get Subfolders from main folder
Set fldLst=fld.SubFolders
'Write first row as columns in CSV file
fl.WriteLine "TestName,TestPath,Status"
'Get each folder path and name to execute the test
For Each f In fldLst
tPath=f.Path 'Get Test Path
tName=f.Name 'Get Test Name
QtApp.open tPath 'Open Test in QTP
QtApp.test.run 'Execute Test
'Write Test result status into CSV file
fl.WriteLine tName&","&tPath&","&QtApp.test.LastRunResults.status
Next
'Close CSV file
fl.Close
'Get CSV File Path
tStatusFilePath=TestsFolderPath&"\"&tFlName
'Create WSH object to open the CSV file
set wsh=CreateObject("wscript.shell")

wsh.Run tStatusFilePath 'Open CSV file


'Release Variables
Set WSH=Nothing
Set f=Nothing
Set fldLst=Nothing
Set fl=Nothing
Set fld=Nothing
Set fso=Nothing
Set QtApp=Nothing
115) Defaults method and common verification in QTP/UFT?
Default
Object Class
Operation
Common Verifications
Window
Activate
Exist, Title
Dialog
Activate
Exist, Title
WinObject
Click
Exist, Text
WinRadioButton Set
Exist, Default Selection
Exist, Default Selection, Items Count, Item
WinTab
Select
Existence
Browser
Sync
Exist
Page
Sync
Exist
Image
Click
Exist, File Name, Alt
Link
Click
Exist, Text
Buttons
Click
Exist, Title, Enabled
Exist, Value, Enabled, Default Value, Max
EditBox
Set
Length, Character Acceptance, Copy Paste
Operations
WebFile
Set
Exist, Value, Enabled, File Path Selection
Exist, Enabled, Default Selection, Multi
WebList
Select
Selection, Items Count, Item Existence
Exist, Enabled, Default Selection, Items
RadioGroup
Select
Count, Item Existence
CheckBox
Set
Exist, Enabled, Default Selection
WebElement
Click
Exist, InnerText
WebTable
GetCellData
Cell Data Verification
116) Web Object in QTP?
During a run session, QuickTest attempts to identify each object in your application by
matching the description properties stored for the corresponding test object with the
properties of the DOM element in the application. For complex Web applications that
contain many objects, using only the standard identification methods may have
unreliable results.
You can instruct QuickTest to use Web object identifiers before the regular object
identification process to help limit thenumber of candidate objects to identify.
QuickTest accesses the application's DOM and returns objects that match the object
identifier property values. QuickTest then continues to identify this smaller set of
returned objects using the normal object identification process. Therefore, using Web

object identifiers can lead to a more reliable and accurate object identification, and a
quicker object identification process.
Web Object Identifier Types
The following Web object identifiers are available:
CSS
CSS (Cascading Style Sheet) is a language used to define formatting of elements in HTML
pages. You can define a CSS identification property value for a test object to help
identify a Web object in your application based on its CSS definition.
QuickTest uses CSS identifiers only when identifying objects and not when learning
objects. Therefore, they are not available from the Object Spy or the Object
Identification dialog box.
User-defined XPath
XPath (XML Path) is a language used to define the structure of elements in XML
documents. You can define an XPath identification property to help identify a Web
object in your application based on its location in the hierarchy of elements in the
Web page. Because of the flexible nature of the language, you can define the XPath
according to the unique way your Web page is structured.
QuickTest uses XPath identifiers only when identifying objects and not when learning
objects. Therefore, they are not available from the Object Spy or the Object
Identification dialog box.
Automatic XPath
You can instruct QuickTest to automatically generate and store an XPath value when
learning Web test objects. During the run session, if the automatically learned XPath for
a particular object results in multiple matches or no matches, the learned XPath is
ignored. Additionally, if you have added a user-defined XPath or CSS identification
property to a test object description, then the automatically learned XPath is ignored.
Automatic XPath is a QuickTest-generated property, and therefore it is not available
from the Object Spy, the Add/Remove Properties dialog box, or the Object Identification
dialog box.
Attribute/* Notation
You can use the attribute/* notation to access custom native properties of Web-based
objects or events associated with Web-based objects.
How to Use Web Object Identifiers - Exercise
In this exercise, you use XPath and CSS identifiers in a test object description to help
locate the correct button in an HTML table.
1.
Prerequisites
a.
Open QuickTest and create a new test.
b. Disable Smart Identification for the Button test object class by selecting Tools >
Object Identification, selecting the Web environment in the Object Identification dialog
box, and then selecting the Button test object class from the Test Object classes list.

<html>
<head>
<style type="text/css">
body { background: green; color: blue; }
.SelectedRow { color: #22444; background: #ebcbeb; width: 450px; }
.RegularRow { color: #444; background: #cbebeb; width: 450px; }
.BPTRow { color: #D9660E; background: #cbebeb; width: 450px; }
</style>
</head>
<body>
<br><br>
<table onclick="javascript:change();" id="maintab">
<tr class="BPTRow" id=BPT>
<td> HP Business Process Testing </td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr class="RegularRow" id=QC>
<td> HP Quality Center </td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr class="SelectedRow" id=QTP>
<td > HP QuickTest Professional </td>
<td> <input type="button" value="Buy"> </td>
</tr>
</table>
</body
</html>
c.
Disable automatic XPath by selecting Tools > Options > Web > Advanced, and then
making sure that the Learn and run using automatic XPath identifiers checkbox is not
selected.

2.
Create a sample Web application
a.
Copy the following syntax content into a text document, and save the document
with an .html extension. The document is saved as an HTML page.
b. Review the appearance and content of your newly created HTML page in any
browser. Make sure that it matches the following image.

3.
Learn the button objects in the Web application
a.
In QuickTest, open the Object Repository Manager, and select Object > Navigate
and Learn. QuickTest is hidden, and the cursor changes to a pointing hand.

b. To verify that QuickTest learned the objects correctly, in the object repository,
select each Button object and select View > Highlight in Application. QuickTest
highlights each button object in the HTML page.
c.
Rename the Button objects to make them more clear:
Rename Buy to Buy_BPT.
Rename Buy_2 to Buy_QC.
Rename Buy_3 to Buy_QTP.

4.
Remove the ordinal identifiers from the button objects
Because all of the Button objects have identical property values, when QuickTest
learned the objects it assigned an ordinal identifier to each test object based on the
location of each object in the application. This may cause QuickTest to identify the
objects incorrectly if the sorting order of the buttons in the application changes.
a.
Select the first button object to display its object properties on the right side of the
object repository window.
b. In the Ordinal Identifier section, select the Browse button. The Ordinal Identifier
dialog box opens.
c.
In the Identifier type drop-down list, select None and close the dialog box. The
ordinal identifier is removed from the test object's identification properties.
d. Repeat steps a - c above for each of the buttons.
e. Verify that the test object descriptions are no longer unique by selecting each test
object and selecting View > Highlight in Application. QuickTest cannot identify the
objects.

5.
Add a CSS identifier based on the object's parent-container
a.
Select the Buy_BPT button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the css property to
the test object description.

c.

Copy and paste the following syntax into the Value edit box:
tr.BPTRow input

6.
Add an XPath identifier based on the object's parent-container
a.
Select the Buy_QTP button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the xpath property
to the test object description.

c.

Copy and paste the following syntax into the Value edit box:
//TR[@id='QTP']/*/INPUT

7.

Add an XPath identifier based on the object's sibling-element

a.
Select the Buy_QC button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the xpath property
to the test object description.
c.
Copy and paste the following syntax into the Value edit box:
//td[contains(concat(' ',text(),' '),'Quality')]/../*/INPUT

8.
Results
Select each object and select View > Highlight in Application. QuickTest can now identify
each button based on the Web object identifiers you added.
Considerations for Working with Web Object Identifiers
General:
Defining xpath and css properties using Frame HTML tags is not supported. This may
cause incorrect identification when identifying Frame objects or
retrieving Frame objects using the ChildObjects method.
xpath and css properties are not supported for .NET Web Forms test objects or for other
Web-based test objects that have .NET Web Forms parent test objects.
When running in Maintenance Mode, QuickTest may replace test objects with XPath or
CSS identifier property values with new objects from your application.
Workaround: Use the Update from Application option in the Object Repository Manager
to update specific test objects with XPath or CSS identifier property values.
Differences Between User-defined XPath and Automatic XPath Behavior During Run
Sessions
Behavior in case of...

User-defined XPath

Automatic XPath

Multiple objects
match the XPath
value

QuickTest continues to identify


the matching objects.

QuickTest ignores the learned


XPath and continues with the
regular object identification
process.

No objects match the Object identification fails, and


XPath value
QuickTest continues to identify
the object using Smart
Identification

QuickTest ignores the learned


XPath and continues with the
regular object identification
process.

ACCESSING CUSTOM PROPERTIES OF WEB-BASED OBJECTS

You can use the attribute/* notation to access custom native properties of Web-based
objects or events associated with Web-based objects. You can then use these properties
or events to identify such objects by adding the notation to the object's description
properties using the Object Identification dialog box, or by using programmatic
descriptions.
Example of using attribute/<property> to identify a Web object
Suppose a Web page has the same company logo image in two places on the page:
<IMG src="logo.gif" LogoID="122">
<IMG src="logo.gif" LogoID="123">
You could identify the image that you want to click by adding the attribute/LogoID notation
to the object's description properties and using a programmatic description to identify the object:
Browser("Mercury Tours").Page("Find Flights")
.Image("src:=logo.gif","attribute/LogoID:=123").Click
(68, 12)
Example of using attribute/<event> to identify a Web object
Suppose a Web page has an object with an onclick event attached to it:
`'alert('OnClick event for edit.');"
You can identify the object by adding the attribute/onclick notation
to the object's description properties and using a programmatic description
to identify the object:
Browser("Simple controls").Page("Simple controls")
.WebEdit("attribute/onclick:= alert\('OnClick event for edit\.'\);").Set "EditText"
114) Using Xpath in qtp?
X- Path Introduction
QTP uses many ways to find an object. X-Path is one of that. In any XML or HTML
document there is a concept called tagging. If you want to create HTML document you
need to go by tags.
For example to create a HTML document you will first create <html> <body> </body>
</html> Tags.
This is the standard for HTML. Like this we have to use TAGS to create any object.
Following to that automatically for every object a hierarchy will be created. This
hierarchy is nothing but XPath.
The x-path for body is /html/body
Example
<html> <body> <table> </table> <table> </table> </body> </html>
In the above code the x-path for the first table is /html/body/Table[1]
XPath (XML Path) is a language used to define the structure of elements in XML
documents. You can define an XPath identification property to help identify a Web object
in your application based on its location in the hierarchy of elements in the Web page.
Because of the flexible nature of the language, you can define the XPath according to the
unique way your Web page is structured.
<html><body>
<table id="maintab" border=1>

<tr id=BPT>
<td>HP Business Process Testing</td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr id=QC>
<td>HP Quality Center</td>
<td><input type="button" value="Buy"></td>
</tr>
<tr id=QTP>
<td >HP QuickTest Professional</td>
<td> <input type="button" value="Buy"> </td>
</tr>
</table></body></html>
The view of above html code is like below

To find the objects of above html we can use complete hierarchy of objects. We can even
simplify the XPaths using X Path Syntax.
XPath Syntax
Expression Description
/

Selects from the root node

//

Selects nodes in the document from the current node that match
the selection no matter where they are

Matches any element node

@*

Matches any attribute Node

Selects attributes

Selects multiple X-Paths

Below table displays path expressions and the result of expressions based on above
html document:
Path Expression

Result

/html

Selects the element html


Note: If the path starts with a slash ( / ) it always represents an
absolute path to an element!

//table

selects all table elements in html document

//TR[@id='QTP']

Selects HP QuickTest Professional table row

//TR[@id='QTP']/*/INPUT Select input tag in the QTP table row and skips elements
between input and table row
//Table | //TR

Selects Table and TR tags

Giving X-Path Property to Identify Objects


To identify Buy button besides Quick Test Professional row we have to use below XPath
//TR[@id="QTP"]//INPUT[@value="Buy"]
In this //TR[@id="QTP"] selects Quick Test Professional Row from all table rows
available in html, //INPUT[@value="Buy"] selects Buy button of all buttons available
in Quick Test Professional Row.
Follow below steps to know how to use XPATH in QTP
Save above html code with a html file
Open the saved html file
Open QTP
Disable smart identification for WebButton class in Tools-> Object Identification
window
Read any of the Buy button to Object Repository
Remove Ordinal Identifier Index for the added button in Object Repository
Click on Property Add (+) in the Object Description Place
Select XPath property
Click on OK
Enter //TR[@id="QTP"]//INPUT[@value="Buy"] at value
Highlight the object in Application
117) Using of Css in Qtp?
The Object Identification for QTP is based on the Recorded Object Description, Visual
Relation Identifiers, Smart Identification and Ordinal Identifiers. You can observe all
these options for all QTP supported environments like Web, Windows, VB, and
Javaetc.
But when it comes to Web Applications there are few more identifiers to identify the
objects. Those are
CSS
User Defined X-Path
Automatic X-Path
Native Properties
CSS (Cascading Style Sheet) is a language used to define formatting of elements in
HTML pages. You can define a CSS identification property value for a test object to help
identify a Web object in your application based on its CSS definition.
For your understanding I have given the below sample on how to use CSS in HTML.
<html>
<head>
<!-- Starting of CSS -->
<style type="text/css">
/* Define h1 tag style */

h1
{
color:orange;
text-align:Left;
}
/* Define CSS Classes */
.MyObject1 { color: #22444; background: #ebcbeb; width: 200px; }
.MyObject2 { color: #22444; background: lightblue; width: 200px; }
</style>
</head>
<body>
<h1>CSS in QTP</h1>
<!-- Specify defined CSS class for object -->
<input type=button class="MyObject1" value="QtpSudhakar">
<input type=button class="MyObject2" value="QtpSudhakar">
</input>
<h1>Sudhakar Kakunuri</h1>
</body>
</html>
In the above html document I have defined a style for h1 tag. Because of that where
ever I have used h1 tags automatically the specified style will be applied there.
I have also created a CSS style classes MyObject1 and MyObject2. I can specify the CSS
style class for any object using class=MyObject1 or class=MyObject2.
Like this we can specify styles to automatically give a specific formatting for Html tags
or we can specify class names for selected objects.
The output of above code is like below

Using CSS Property for QTP Objects


Follow below steps to know how to use CSS in QTP
1)
Save above html code with a html file
2)
Open the saved html file
3)
Open QTP
4)
Disable smart identification for WebButton class in Tools Object Identification
window
5)
Read the both QTPSudhakar buttons to Object Repository

6)

Remove Ordinal Identifier Index for both the buttons in Object Repository

There will be two QtpSudhakar buttons created because there are duplicate buttons with
the name of QtpSudhakar. We differentiate these buttons based index. But index is not
reliable if more objects are added. But we can use CSS property to differentiate both the
objects. Continue to below steps
7)
8)

Select QtpSudhakar Button in Object Repository


Click on Property Add (+) in the Object Description Place

9)

Select CSS property

10) Give .MyObject1 in the value column

11) Select QtpSudhakar_2 Button in Object Repository


12) Click on Property Add (+) in the Object Description Place
13) Select CSS property
14) Give .MyObject2 in the value column
15) Highlight both the objects
118) What is Method overriding in qtp?
Method Overriding is one of the core features of Object Oriented Programming where
you can replace the original/default implementation of a function with your own
implementation. In other ways, your new function would override the code or logic of
the original function. As an example, consider the addition operation which would give
you the sum of a set of numbers. To override this operation, you can create a function
(say fnSum) which would not only find the sum of numbers, but it would also save the

sum in an external file or maybe display in a message box. Lets see how you can do this
in QTP.
Method Overriding in QTP
You can use QTPs RegisterUserFunc statement to achieve method overriding in your
scripts. Consider a scenario where you want to click on a web button in your
application. Now you can override the default Click method with a function that first
checks whether the web button exists or not. If it exists, then it checks that the button
should be enabled. After both these validations are done, comes your code to click on
the button. Lets see the sample code for this scenario 1
'===== Code in Function Library =====
2
RegisterUserFunc "WebButton", "fnBtnClick", "fnBtnClick"
3
4
'Function Definition
5
Function fnBtnClick(objControl)
6
7
'<nobr><a id="PXLINK_5_0_4" class="pxInta" href="#">Check</a></nobr> if object exists
8
If objControl.Exist Then
9
'Check if the object is enabled or not
10
If objControl.GetROProperty("disabled") <> 0 Then
11
'Click on the button
12
objControl.Click
13
End If
14
End If
15
16
End Function
17
18
'===== Sample code in your action =====
19
Browser("Browser").<nobr><a id="PXLINK_2_0_1" class="pxInta" href="#">Page</a></nobr>("Page"
From the above code, you would see that we have created a function fnBtnClick which
overrides the default click operation. This function clicks on the button only when you it
exists in the application as well as it is enabled.
Method Reuse in QTP
This is another cool feature that you can actually implement using RegisterUserFunc
statement. This concept is slightly different from the normal function reuse where you
create a function for a reusable scenario and then call this function wherever required.
With RegisterUserFunc, you create a generic function and then bind this function with
different controls. For example, you can create a generic fnClick function and then bind
the function with a web button, link, image, web element etc. This way you can use the
same function for different controls.
1
'===== Code in Function Library =====
2
RegisterUserFunc "WebButton", "fnClick", "fnClick"
3
RegisterUserFunc "Link", "fnClick", "fnClick"
4
RegisterUserFunc "Image", "fnClick", "fnClick"
5
6
'Function Definition
7
Function fnClick(objControl)
8
objControl.Click
9
End Function

10
11
'=====Code in Action =====
12
Browser("Browser").Page("Page").WebButton("btn1").fnClick
13
Browser("Browser").Page("Page").Link("lnk1").fnClick
14
Browser("Browser").Page("Page").Image("img1").fnClick
In the above example, we have created a single function fnClick which is being used by
different controls like Web Button, Link, Image etc.
It would be better to read function libraries (if you dont know what these are) before
going down further.
What do you mean by Registering a Function?
You can register a public function to a test object to enable the function
(operation) to be performed on a test object.
What are the ways to register a function in QTP?
Register a function through Function Definition Generator.
Register a function manually.
How to register a function manually? Give examples.
You can manually register your function to a test object by adding a
RegisterUserFunc statement after your function as shown in the following
example:
RegisterUserFunc "WebEdit", "MySet", "MySetFunc"
In this example, the MySet method (operation) is added to the WebEdit test
object using the MySetFunc userdefined
function. If you or the Subject Matter
Expert choose the WebEdit test object from the Item list in the Keyword View, the
MySet operation will then be displayed in the Operation list (together with other
registered and out of the box operations for the WebEdit test object), or if in the
Expert View, you press dot (period) after webedit object, you will get MySet in the
IntelliSense dropdown
list.
RegisterUserFunc: Enables you to add new methods to test objects or change
the behavior of an existing test object method during a run session. When you use
this statement, QuickTest uses your userdefined
function as a method of a
specified test object class for the remainder of a run session, or until you
unregister the method.
Another RegisterUserFunc example with little bit more detail
This may not be useful in real word scenario, but it is just a simple example to
give you a feel of RegisterUserFunc.
See the below screenshot. It shows all the operations which you can apply on a Page
object (also known as IntelliSense). Just write the below line in QTP and press dot
(period).

If you write some function and register it to any test object as shown below, it shows up
with all the default operations in IntelliSense popup. Just write the below code in QTP
and press dot (period). You dont have to Run anything. Here the my_multiply method
(operation) is added to the Page test object using the multiply userdefined function.
[see the below screenshot my_multiply is shown
in IntelliSense popup]

Important points about registering a function


1. You can choose to override the functionality of an existing operation. For
example you can write your own CheckProperty function and override its default
functionality.
2. When you register a function to a test object, you can optionally define it as the
default operation for that test object. This instructs QuickTest to display the
function in the Operation column (Keyword View), by default, when you choose
the associated test object in the Item list. In Function Definition Generator,
register by checking the checkbox as shown below:

And manually to define a function as the default function, you define the value of
the fourth argument of the RegisterUserFunc statement as True. For example:
RegisterUserFunc "WebEdit", "MySet", "MySetFunc", True
3. A registered or global function can only be called from a test or component after
it is added to the test script or a function library that is associated with the test or
the component's application area.
4. QuickTest clears all function registrations at the beginning of each run session.
5. When you register a function, it applies to an entire test object class. You CANNOT
register a method for a specific test object.
6. If you want to call a function from additional test objects, you can copy the
RegisterUserFunc line, paste it immediately after another function and replace any
relevant argument values.
7. If the function you are registering is defined in a function library, it is
recommended to include the RegisterUserFunc statement in the function library as
well so that the method will be immediately available for use in any test using that
function library.
8. You can reregister the same method to use different userdefined functions without
first unregistering the method. However, when you do unregister the method, it resets
to its original QuickTest functionality (or is cleared completely if it
was a new method), and not to the previous registration.
9. If you register a method within a reusable action, it is strongly recommended to
unregister the method at the end of the action (and then reregister it at the beginning of
the next action if necessary), so that tests calling your action will not
be affected by the method registration.
How to unregister a function?
To unregister a function simply use UnRegisterUserFunc:
To unregister my_multiply function from our above example use:
unRegisterUserFunc "Page", "my_multiply"
UnregisterUserFunc: Instructs QTP to stop using the current registration of the method.
If the unregistered method is a defined QTP method for the object, the functionality of
the method returns to the standard QTP functionality.
121) Ways To associate Function Library in QTP?
4 Different Ways to Associate Function Libraries to your QTP Scripts
Most of the times, when you are creating test scripts or are designing a new QTP
Framework, you would be trying to come up with reusable functions which you would
have to store in the function library. Now, in order to use this function library with

multiple test cases, you need to associate this function library with your scripts. This
article explains the 4 methods that will help you in associating the function libraries in
QTP Test Cases.
Based on the type of framework you are using, you can use any of the following
methods to associate function libraries to your QTP Script 1) By using File > Settings > Resources > Associate Function Libraryoption in QTP.
2) By using Automation Object Model (AOM).
3) By using ExecuteFile method.
4) using LoadFunctionLibrary method.

Lets see in detail how each of these methods can be used to map function libraries to
your test scripts.
1. Using File > Settings > Resources > Associate Function Library option from the Menu
bar
This is the most common method used to associate a function library to a test case. To
use this method, select File > Settings option from the Menu bar. This will display the
Test Settings window. Click on Resources from the left hand side pane. From the right
hand side pane, click on the + button and select the function library that needs to be
associated with the test case.
Associate function Library to QTP
2. Using AOM (Automation Object Model)
QTP AOM is a mechanism using which you can control various QTP operations from
outside QTP. Using QTP Automation Object Model, you can write a code which would
open a QTP test and associate a function library to that test.
Example: Using the below code, you can open QTP, then open any test case and
associate a required function library to that test case. To do so, copy paste the below
code in a notepad and save it with a .vbs extension.
1
'Open QTP
2
Set objQTP = CreateObject("QuickTest.Application")
3
objQTP.Launch
4
objQTP.Visible = True
5

6
7
8
9
10
11
12
13

'Open a test and associate a function library to the test


objQTP.Open "C:\Automation\SampleTest", False, False
Set objLib = objQTP.Test.Settings.Resources.Libraries
'If the library is not already associated with the test case, associate it..
If objLib.Find("C:\SampleFunctionLibrary.vbs") = -1 Then ' If library is not
already added
objLib.Add "C:\SampleFunctionLibrary.vbs", 1
' Associate the library to the test case
End

3. Using ExecuteFile Method


ExecuteFile statement executes all the VBScript statements in a specified file. After the
file has been executed, all the functions, subroutines and other elements from the file
(function library) are available to the action as global entities. Simply put, once the file is
executed, its functions can be used by the action. You can use the below mentioned logic
to use ExecuteFile method to associate function libraries to your script.
'Action begins
1
ExecuteFile "C:\YourFunctionLibrary.vbs"
2
3
'Other logic for your action would come here
4
5
'.....

1
2
3
4
5
6
7
8

4. Using LoadFunctionLibrary Method


LoadFunctionLibrary, a new method introduced in QTP 11 allows you to load a function
library when a step runs. You can load multiple function libraries from a single line by
using a comma delimiter.
'Some code from the action
'.....
LoadFunctionLibrary "C:\YourFunctionLibrary_1.vbs" 'Associate a single function library
LoadFunctionLibrary "C:\FuncLib_1.vbs", "C:\FuncLib_2.vbs" 'Associate more than 1
function libraries
'Other logic for your action would come here
'.....
123) Write a program to find a reverse a string without using strreverse?
Recently one of my colleagues put an interesting situation to script in vbs. It was to
reverse a string without using Mid or string Reverse function. For example, if the given
string is AUTOMATED 360 , the result should be DETAMOTUA 063.
Since most of us are likely to use the built in functions and not to think about other ways
of doing the same, it sounds like a bit tough. I also had the same situation, but a
few minutes of analysis resulted me the solution for the same. The trick is to put all the
characters in array and then print the array in reverse order.
below is the code using array to reverse the string.

1 msgbox ReverseString(360" "AUTOMATED)


2
3 ReverseString Name: 'Function
4 functions. mid or Reverse String using without string the reverse for call to
5 Function Main 'Description:
6 wString(String) 'Input:
7 ReverseString(String) 'Output:
8 [Automated-360.com] Kumar Saket 'Author:
9 Function ReverseString(wString)
10 the Split 'wordsarray in put to string in
11
wStringArr = Split(wString, " ")
12
For nCnt = 0 to UBOUND(wStringArr)
13
array in word of letters the all 'Put
14
MyArr = singleCharArr(wStringArr(nCnt))
15
order reverse in array 'Print
16
for n = UBOUND(MyArr) to 0 step -1
17
str = str &amp; MyArr(n)
18
next
19
str = str &amp; " "
20
Next
21
ReverseString = str
22 End Function
23
24 singleCharArr Name: 'Function
25 array an into string a of letters all put to Function 'Description:
26 inputString(String) 'Input:
27 singleCharArr(array) 'Output:
28 [Automated-360.com] Kumar Saket 'Author:
29 Function singleCharArr(inputString)
30
blank is input if 'Check
31
If inputString &lt;&gt; "" then
32
Dim oRegEx, colChars
33
Set oRegEx = New RegExp
34
oRegEx.Global = True
35
oRegEx.IgnoreCase = True
36
oRegEx.Pattern = ".{1}"
37
Set colChars = oRegEx.Execute(inputString)
38
Dim arrChars()
39
For i = 0 to colChars.Count - 1
40
Redim Preserve arrChars(i)
41
arrChars(i) = colChars.Item(i)
42
Next
43
Set colChars = Nothing
44
Set oRegEx = Nothing
45
singleCharArr = arrChars

46
47

Erase arrChars
End If
End Function
Here is one more nice way to do this using array again.

1 wString = "AUTOMATED 360"


2 arrPar = Split(wString, " ")
3 arrParRev = Split(wString, " ")
4 For n = 0 to UBOUND(arrPar)
5
For i = 32 to 122
6
if not i = 35 then
7
arrPar(n) = replace(arrPar(n), Chr(i), Chr(i) &amp; "#")
8
end if
9
Next
10
arr = Split(arrPar(n), "#")
11
arrRev = Split(arrPar(n), "#")
12
For j = UBOUND(arr) to 0 step -1
13
arrRev(UBOUND(arr)-j) = arr(j)
14
Next
15
arrParRev(n) = join(arrRev, "")
16 Next
17 y = join(arrParRev, " ")
18 msgbox y
125) How do you assign a Shared Object Repository to an action?
You can associate a single action with an object repository by rightclicking
The action in the Resources pane and choosing Associate repository with action from
the context menu.
You can use the Associated Repositories tab of the Action Properties dialog box
(Edit > Action > Action Properties) to associate one or more object repositories
with the current action etc.
126) How can I highlight a Test Object and make it flash?
You can select a test object in your object repository and highlight it in the
application you are testing. When you choose to highlight a test object, QuickTest
indicates the selected object's location in your application by temporarily showing a
frame around the object and causing it to flash briefly.
Make sure your application is open to the correct window or page.
Select the test object you want to highlight in your object repository.
Click the Highlight in Application button or choose View > Highlight in Application.
The selected object is highlighted with a border in the application.
127) Explain an action parameter?
Test/action parameters: Test parameters make possible for us to use values
passed from the test.

Action parameters enable us to pass values from other actions in your test.
To use a value within a specific action, the value must be passed down through the
action hierarchy of the test to the required action.
We can then use that parameter value to parameterize a step in the test.
For example, suppose that we want to parameterize a step in Action3 using a value i.e
passed into the test from the external application that runs (calls) the test.
We can pass the value from the test level to Action1 (a top level action) to Action3 (a
nested action of Action1), and then parameterize the required step using this action
input parameter value (that was passed through from the external application).
Alternatively, we can pass an output action parameter value from an action step to a
later sibling action at the same hierarchical level.
For example,suppose that Action2, Action3, and Action4 are sibling actions at the same
hierarchical level, and that these are all nested actions of Action1.
We can parameterize a call to Action4 based on an output value retrieved from Action2
or Action3.
We can then use these parameters in the action step.
128) What are the challenges you have faced in automating test cases? and the
resolution?
as a automation test engineer,most of the times we get object
recognition problem. In our applications some pages having
dynamic objects(we can handling using DP). Some pages having
Custom objects (we can change custom to standard using virtual
objecct concept). 1. What to test and what not to test
2. Object recognition
3. Dynamic objects
4. System is not stable
5. Communication
these are the challenges I faced while doing automation testing
Keeping Automation Test Cases Up-To-Date With more and more development cycles adopting an Agile approach the automation
suite has to always have as up-to-date test cases as possible. Unfortunately for those
who think automation means that you can set and forget your software testing Im sorry
to inform you but there always be some amount of maintenance needed on your
automation scripts. The simple fact that any change to the DOM elements can halt an
automation script in its tracks means your testers need to have an intimate
understanding of how the scripts are interacting with the application under test so they
can quickly identify issues, correct them, and re-validate the test. It is always a good
practice to create detailed documentation for all test cases in the automation suite to
help facilitate the debugging process.
What is the toughest QTP challenge that you have faced?
Will: My toughest QTP challenge is the same challenge we all face continually. How do
we create maintainable tests that produce meaningful and reliable results from one
software release to the next? Like most people here, my first QTP test was a recordand-playback script that errored out the second time it ran. That started the challenge
to create better tests. Ive made pretty good progress on this challenge, but there is still
a lot left to do.

129) How to work with custom controls?


QTP identifies windows object using their classes. All default class map to a specified
window Test object in QTP. Ex The Edit class maps to WinEdit test object, Static
class maps to the Static Test object.
Objects inside applications developed using standard windows API can be easily
identified and automated through QTP.
But at times applications deviate from using the standard
standard classes and give custom
names to the classes, though the underlying architecture for the control remains the
same.
This article will walk you through the process of mapping custom test object class to
pre-defined
defined QTP test objects. To demonstrate th
thee same I would use the Windows XP
search files & folder example

Custom control in Windows XP Search window


Recording on the checkbox in Windows XP Search window will produce below code in
expert view
Visual Basic
1 Window("Search Results").WinObject
WinObject("Search hidden files and").Click 5,5
5
WinObject test object is a generic window test object which QTP uses when it is not able
to identify the object as a pre-defined
defined test object. If we look at the object using object
spy we will notice the class of the object as SA_Button

Custom control object spy


Since this class name is a custom class name, we now need to map it to WinCheckBox.
To do the same follow the below steps
Open QTP
Go to Tools->Object
>Object identification
Select the Environment as Standard windows
Click on the User-Defined
fined button
Use the hand pointer to point to the object and fetch the object class
Select the Map to: as Checkbox and click on the Add button
Click OK

Mapping Custom Object class to QTP test object


Now lets re-record
record on the application. The code now generated in expert view would be
as below
Visual Basic
Window("Search Results").ActiveX
ActiveX("Search Assistant Control").WinCheckBox
WinCheckBox("Search
1
hidden files and").Set "ON"

Object spy of custom control after mapping to QTP test object


So we were successfully able to map a custom control to a windows control.
Key points to note
Though this approach worked in our case, it might not in all the case. Reason could be
use of custom message in the underlying control making it impossible for QTP
to work with the same
After mapping the object make sure all the properties and methods are working as
expected
User-Defined
Defined object mapping setting is specific to machine and needs to be applied to all
machines which will be used for running the script
130) You are given a sealed script, to which youre
youre supposed to add the following
functionality whenever a combobox is inputed, a report should be made to the log.
How would you achieve that?
A3. Through RegisterUserFunc overrun the comboboxs default Select method.
131)You dont know how many WebEdits are in a page,, but you have to fill them all up.
How can you do that?
A1. Using Descriptive Programming with .ChildObjects to get the objects, then looping
through them
132) How would you automate a non-standard
non
web / java / .net control?
A2. Use object exploration techniques in the Runtime-Object
Runtime
level
133) What is .Net Windows Forms Spy? and how it is different from object spy?
Using the .NET Windows
ndows Forms Spy The .NET Windows Forms Spy enables you to view
details about selected .NET Windows Forms controls and their run-time
run time properties. You
can use the .NET Windows Forms Spy to help you develop extensibility for .NET
Windows Forms controls. You can
can use the .NET Windows Forms Spy when planning
.NET Add-in
in extensibility implementation to create support for custom .NET Windows
Forms controls. The .NET Windows Forms Spy assists you in examining .NET Windows
Forms controls within your application. It also
also enables you to see which events cause
your application to change (to facilitate record and run extensibility implementation)

and how the changes manifest themselves in the control's state. You access the .NET
Windows Forms Spy by choosing Tools > .NET Windows Forms Spy in the main
QuickTest window.Chapter 1 Introducing QuickTest Professional .NET Add-in
Extensibility 19 Note: To spy on a .NET Windows Forms application, make sure that the
application is running with Full Trust. If the application is not defined to run with Full
Trust, you cannot spy on the .NET applications Windows Forms controls with the .NET
Windows Forms Spy. For information on defining trust levels for .NET applications,
refer to Microsoft documentation. For more information on the .NET Windows Forms
Spy, see the HP QuickTest Professional Add-ins Guide.
133)How to test XMLs in QTP?
XML is a markup language designed for how to store data that is in the form that both
human and machine readable format. Using XML, data can also be easily exchanged
between computer and database systems.
Sample XML and their key elements

are represented below:


Accessing XML
Const XMLDataFile = "C:\TestData.xml"
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)
' Getting the number of Nodes (books)
Set nodes = xmlDoc.SelectNodes("/bookstore/book")
Print "Total books: " & nodes.Length ' Displays 2
' get all titles
Set nodes = xmlDoc.SelectNodes("/Booklib/book/value/text()")
' get their values
For i = 0 To (nodes.Length - 1)
Title = nodes(i).NodeValue
Print "Title is" & (i + 1) & ": " & Title
Next

Comparing XML
We can compare Two given xml's.
Dim xmlDoc1
Dim xmlDoc2
' Load the XML Files
Set xmlDoc1 = XMLUtil.CreateXMLFromFile ("C:\File1.xml")
Set xmlDoc2 = XMLUtil.CreateXMLFromFile ("C:\File2.xml")
'Use the compare method of the XML to check if they are equivalent
Comp = xmlDoc1.Compare (xmlDoc1, xmlDoc2)
'Returns 1 if the two files are the same
If Comp = 1 Then
Msgbox "XML Files are the Same"
Else
Msgbox "XML Files are Different"
136) What is COM interface? Does QTP has COM interface? have you used it?
COM interface appears in the scenario of front end and back end. for eg: if you r using
oracle as back end and front end as VB or any language then for better compatibility we
will go for an interface of which COM will be one among those interfaces. Create object
creates handle to the instance of the specified object so that we program can use the
methods on the specified object. It is used for implementing Automation
137) In how many ways you can call an action? which one you will prefer?
RunAction ActionName, [IterationMode , IterationRange , Parameters]
Here the actions becomes reusable on making this call to any Action.
IterationRange String Not always required. Indicates the rows for which action
iterations will be performed. Valid only when the IterationMode is rngIterations. Enter
the row range (i.e. "1-7"), or enter rngAll to run iterations on all rows.
If the action called by the RunAction statement includes an ExitAction statement, the
RunAction statement can return the value of the ExitAction's RetVal argument.
Using "Call to Existing Action" we can call one action from another action.
Go to Insert ->select Call to Existing Action
Select which action wants to call.
139) How to run multiple instances of application how to differentiate the instances?
We are aware of that multiple instances of QTP can't be running on a single machine.
But by using QTP we can work with multiple instances of the Application Under Test.
For example, QTP can handle multiple browsers or multiple applications at a time.
We can work with 2 applications at a time even without stopping the recording. We
should make sure that we configured both Record and Run on any opened
applications(Both Windows and Web) under Automation>Record And Run Settings>
Select the radio button "Record and Run on any application for both Windows and
Web".
We have to keep it in our mind that we can't run multiple instances of QTP on a single
machine.But we can handle multiple browsers or applications by using single QTP
instance.

within loop
use Systemutil.run "Apppath"
or use Invokeapplication("Apppath")
to recognize the application object - use index property.
ex: In case of Browser use Creation time
140) when tests run as batch, qtp shows the last run result only. how to get the results
for the each an every script?
Simple way is using MTM (Multi Test Manager) where you will build a test suit and then
simple hit on Run, which will execute the scripts and give you the status report. But, we
have to make sure that the results path is not pointing to Temp.
2) Develop a custome reporting where all the steps will be stored in your desired
location.
If you don't want to change your current code, then you can change the results folder to
you desired folder where you want to see the Results, once you are done with scripts
execution you can access all the execution reports.
'Create the Run Results object
set oQTPResultsLoc = CreateObject("QuickTest.RunResultsOptions")
'Make sure that you have the required folders for results storing.
'In this example C:\Test Results is the folder where I want to store my results with Test
Case name.
'Now change the results location
oQTPResultsLoc .ResultsLocation "C:\Test Results\" & Environment("TestName")
Start QTP, Open an Existing Test and Get All Available Action Names From the
Test:
Dim qtApp
'Create the QTP Application object
Set qtApp = CreateObject("QuickTest.Application")
'If QTP is notopen then open it
If qtApp.launched <> True then
qtApp.Launch
End If
'Make the QuickTest application visible
qtApp.Visible = True
qtApp.Open "C:\Program Files\HP\QuickTest Professional\Tests\trial", False, False
'Get count of Action in a test
oActCount=qtApp.Test.Actions.Count
For iCounter=1 to oActCount

' Get the first action in the test by index (start from 1)
MsgBox qtApp.Test.Actions(iCounter).Name
Next
'Close QuickTest
qtApp.Quit
' Release the Application object
Set qtApp = Nothing
140) QTP-Qc integration
QTP-QC Integration:
In this section, we are going to learn how to integrate QTP and QC. By Integrating, the
QTP automation scripts can be executed right from Quality Center. For establishing a
connection, first step is to install the required Addins. We will understand how to
integrate by taking a sample QTP script and execute it from QC.
Step 1: Navigate to ALM home page and click on "Tools" from the list of links.

Step 2: Click on "More HP ALM Addins" Link from the addins page as shown below.

Step 3: In the Addins page, select "Addins for HP applications" and choose "Quick Test
Professional". In case of "Unified Functional testing" (UFT), choose the options
appropriately and install the addins. The Installation is similar to HP-MS Office Addins.

Step 4: Establish a connection between QTP and QC by Navigating to "File" >> "ALM/QC
Connection".

Step 5: HP ALM Connection dialog opens. Enter the Server URL as shown in the below
example.

Step 6: Once the URL is correct, the credientials dialog opens. Tester has to connect to
the relevant project area.

Step 7: Once ALM Connection is successful, we need to save the Driver Script in Quality
Center. Select ALM/QC Plan as shown below.

Step 8: Once the test is saved, we can see the in ALM where the test type is shown as
"Quick Test".

Step 9: Upon Navigating to "Test Script" Tab which appears only if the test type is of
"Quick Test", The script shown in QTP screen would be displayed in Quality Center as
well.

Step 9: The other necessary component that is required for script execution is Library
files which can be placed under "Test Resources" Folder.

Step 10: The Function Library file can be added by creating a new resource of type ".qfl"
or ".vbs" .

Step 11: The Added library file can be accessed in quality Center using resource Viewer.

Step 12: If there are more library files, the same is added by creating a new resource of
type ".qfl" or ".vbs".

Step 13: Once again, Added library file can be accessed in quality Center using resource
Viewer.

Step 14: The Next dependant component for any script execution is "Object Repository"
which is again placed under "Resources" section.

Step 15: The added Object Repository and its properties can be viewed using "Resource
Viewer".

Step 16: The Datatable, parameterized data setup also be placed in Quality Center
under "Test Resouces" section.

Step 17: The added data Table can be viewed using in "Resource Viewer".

Step 18: The Datatable should now also be mapped to the test settings so that they can
be picked while execution. The same can be done using "Settings" of "File" Menu.

Step 19: The Test Settings dialog opens. Navigate to Resources Tab and select the
Datatable that we added in Step 16.

Step 20: Now we can access those test resources that are uploaded in Quality Center in
QTP script as shown below. The Libraries files and Object Repositories are binded
dynamically.

Step 21: Now, we should allow QTP to interact with other Hp Products. This will allow
QTP to interact with Quality Center. Goto "Tools" >> "Options"

Step 22: Now, enable "Allow other HP products to run tests and components" as shown
below.

Step 23: The Next Step is to add the test in "Test Lab" and execute the test. The
Procedure to Add tests into Test Lab remains the same as that of manual tests.

Step 24: Upon Clicking on "Run", the automatic runner opens and enable "Run all tests
locally" and hit "Run".

Step 25: Once execution is complete, the test result is displayed on the the same
"Automatic Runner" dialog.

Step 26: In Test Lab QTP report is loaded automatically. User can click on "Launch
report" to get to know about more details of the execution.

145) How can we automatically connect QTP with QC on start up?


A: Go to File > Quality Center Connection. Check the box marked Reconnect to server

on start-up.
146) What if QTP tries to connect with QC automatically but QC login credentials had changed?
A: Change the following properties from 1 to 0. They are present in mic.ini file under
QTP installation generally found under C:Program FilesMercury InteractiveQuickTest
Professionalbin
LoginAutomatically=0
ReconnectToDB=0
ReconnectToServer=0
147) How can we access Quality Center Open Test Architecture (OTA) using AOM?
A: Using QCUtil object (AKA TDUtil for QTP 6.5 and backwards). You can find details of
all associated properties like CurrentRun, TestRun, Current Testset, CurrentTestSetTest,
IsConnected, QCConnection under QTP Help > Quick Test Object Model Reference > Utility
Objects > QCUtil Object.
Qqqq: Where can we find all methods and properties present under TDConnection
Object?
A: Refer QTP Help > QTP Advanced References > QuickTest Automation >
TDConnection Object.
QQ: How can we upload QTP scripts to QC using AOM?
A: Once connected to Quality Center, open the test using AOM and save it to QC.
Example:
qtqcApp.Open "C:TempProjectQTPTestScript1", True
' Get the Test object

Set qtqcTest = qtqcApp.Test


' Use the SaveAs method to upload the test to Quality Center
qtqcApp.Test.SaveAs "[QualityCenter] SubjectFolderNameQTPTScript"
Q: Which version of QTP is compatible with which version of Quality Center?
A: QC 9.0 integrates with QTP 8.2 SP1, QTP 8.2 SP2, QTP 9.0, QTP 9.1 and QTP 9.2. To
check the compatibility of your QTP version, check out the ReadMe that comes preinstalled with QTP
Q: Can we record Quality Center operations with QTP
A: Yes, only with QC 9.2 and above. Use .NET Add-in.
Q: Can we schedule a test run from Quality Center?
A: Yes, use Test Run Scheduler utility that comes with QC.
Q:QIs there version control in QC with QTP?
A: Yes, QTP 10.0 provides you the version control feature under the name of Quality
Center Version Control present under File Menu. Earlier versions of QTP can work
with 3rd party version control tools.
Test Lab Module in QC Part3: Running Automated Scripts from Test Lab
This is in continuation of our series of articles on Test Lab Module in QC and it is the last
article of series. In the first article we saw how to create a test set, move scripts from
test plan and run them manually, in the second article we discussed how to log defects
from test lab module
In this article well see how we can run automated QTP scripts from Test Lab in QC.
Before you try to run your automated scripts from test lab, you need to make sure that
your tool (QTP/ WinRunner ) is connected with Quality Center. Here are the steps to
connect QC to QTP.
First you need to ensure that Allow other Mercury products to run tests and
components option present under Tools > Options > Run in QTP is checked.
If you are running the tests on the same computer where you have QC client installed,
then you will need:
QTP Connectivity Add-In
QTP Add-in
If you are running the tests on the different computer than where you have QC client
installed, then you will need:
QTP Add-in where QC client is installed.
QTP Add-in and QC connectivity Add-in where QTP is installed.
QC connectivity can be found at QC server URL > Add-Ins Page link > QC Connectivity
link > Download Add-in. QTP Add-in can be found at QC server URL > Add-Ins Page
link > More QC Add-ins link > Download and install QTP Add-in according to its
version.
We will now see how to execute the automated test scripts from the test lab module.
(Click on the individual images below to view them in full size, press Esc key to return)

Navigate to Test Plan module in QC.

Create a folder under the root folder and right click to create a new test as shown below.

Once New test option is clicked a pop up appears as shown below. In the Test Type box,
select QUICKTEST_TEST to create a Quick Test Professional test, or select WRAUTOMATED to create a

WinRunner test.

In the Test Type box, select QUICKTEST_TEST to create a Quick Test Professional test, or
select WR-AUTOMATED to create a Win Runner test.

Once Test Name is provided and user clicks on OK.It takes to the next step where we
need to provide the description as shown below.

Once the user clicks on OK, a test is created as shown below.

Once the automated test case is created. Click on Test Script tab present on the right
hand side.A script is generated based on the design steps of the test case as shown
below.

Navigate to Test Lab module present on the left hand side of the application.

Navigate to the folder created and add a test set Test as shown below.

Right click and select the option Select tests which open a test plan tree as shown
below.

Select the tests from the test set by clicking on the left arrow in the test plan tree
present on the right hand side.

The selected test will appear in the test set.

Select the required test case and click on the Run button present on the top, below the
menu bar.

The automatic runner pop up opens up, where the test to be run will be selected. Then
click on Run.

This connects to the automation tool which is integrated with the QC application and
gives us the result of the run for the particular test case.
When a test has finished running you can view the test results in your selected
testing tool
To view the test results in Quick Test Professional, click the Launch Report button.
To view the test results in Win Runner, click the View Report button.
Test Lab Module in QC Part2: Logging Defects from test lab
This is in continuation of our series of articles on Test Lab Module in QC. In the first
article we saw how to create a test set, move scripts from test plan and run them
manually
In this article well see how we can raise a new defect from the test lab itself for a
particular script. (Click on the images below to view them in full size. Press Esc key
when you wish to return to the article)
Once you find a particular test case is a failure and youre sure its a defect, then follow
the steps mentioned below.

Click on the option Run > Select Run Manually from the drop down list.

Click on Begin Run as shown below.

If any/all steps are failing for a test case then update the status as Fail Selected/Fail
Allas per the snapshot shown below.

Once the status is updated as Failed click on the New Defect option present beside
the attachment section.

A new window opens. You would need to input the details of the issue in various fields
given below and hit Submit.

SQL questions for interview


Create the following Tables:
LOCATION

Location_ID Regional_Group
122

NEW YORK

123

DALLAS

124

CHICAGO

167

BOSTON

DEPARTMENT
Department_ID
10
20
30
40
JOB
Job_ID
667
668
669
670
671
672

Name
ACCOUNTING
RESEARCH
SALES
OPERATIONS

Location_ID
122
124
123
167

Function
CLERK
STAFF
ANALYST
SALESPERSON
MANAGER
PRESIDENT

EMPLOYEE
EMPLOYEE_ID LAST_NAME FIRST_NAME MIDDLE_NAME JOB_ID MANAGER
7369

SMITH

JOHN

667

790

7499

ALLEN

KEVIN

670

7698

7505

DOYLE

JEAN

671

7839

7506

DENNIS

LYNN

671

7839

7507

BAKER

LESLIE

671

7839

7521

WARK

CYNTHIA

670

7698

based on the above tables:


Simple Queries:
1.List all the employee details : Select * from employee
2.List all the department details : Select * from department
3.List all job details : Select * from job
4.List all the locations : Select * from loc
5.List out first name,last name,salary, commission for all employees:Select first_name,
last_name, salary, commission from
employee
6. List out employee_id,last name,department id for all employees and
rename employee id as ID of the employee, last name as Name of
the employee, department id as department ID: : Select employee_id id of the
employee, last_name name", department id as department id from employee
7. List out the employees anuual salary with their names only.: Select last_name,
salary*12 annual salary from employee
Where Conditions:
8. List the details about SMITH: Select * from employee where last_name=SMITH
9. List out the employees who are working in department 20: Select * from employee
where department_id=20;
10. List out the employees who are earning salary between 3000 and 4500:
Select * from employee where salary between 3000 and 4500
11. List out the employees who are working in department 10 or 20
12. Find out the employees who are not working in department 10 or 30:
Select * from employee where department_id in (20,30)
Select last_name, salary, commission, department_id from
employee where department_id not in (10,30)
13. List out the employees whose name starts with S:
Select * from employee where last_name like S%
14. List out the employees whose name start with S and end with H
Select * from employee where last_name like S%H
15. List out the employees whose name length is 4 and start with S
Select * from employee where last_name like S___
16. List out the employees who are working in department 10 and draw the
salaries more than 3500
Select * from employee where department_id=10 and
salary&gt 3500
17. list out the employees who are not receiving commission.

Select * from employee where commission is Null


Order By Clause:
18. List out the employee id, last name in ascending order based on the
employee id.:Select employee_id, last_name from employee order by
employee_id
19. List out the employee id, name in descending order based on salary
Column : Select employee_id, last_name, salary from employee order
by salary desc
20. list out the employee details according to their last_name in ascending
order and salaries in descending order: Select employee_id, last_name, salary from
employee order
by last_name, salary desc
21. list out the employee details according to their last_name in ascending
order and then on department_id in descending order.: Select employee_id, last_name,
salary from employee order by last_name, department_id desc
Group By &amp Having Clause:
22. How many employees who are working in different departments wise in
the organization: Select department_id, count(*), from employee group by
department_id
23. List out the department wise maximum salary, minimum salary,
average salary of the employees :Select department_id, count(*), max(salary),
min(salary),avg(salary) from employee group by department_id
24. List out the job wise maximum salary, minimum salary, average
salaries of the employees.:Select job_id, count(*), max(salary), min(salary), avg(salary)
from employee group by job_id
25. List out the no.of employees joined in every month in ascending order.:Select
to_char(hire_date,month)month, count(*) from
employee group by to_char(hire_date,month) order by month
26. List out the no.of employees for each month and year, in the ascendingorder based
on the year, month.:Select to_char(hire_date,yyyy) Year,
to_char(hire_date,mon) Month, count(*) No. of employees from
employee group by to_char(hire_date,yyyy), to_char(hire_date,mon)
27. List out the department id having atleast four employees.:Select department_id,
count(*) from employee group by department_id having count(*)&gt=4
28. How many employees in January month.:Select to_char(hire_date,mon) month,
count(*) from employee group by to_char(hire_date,mon) having
to_char(hire_date,mon)=jan
29. How many employees who are joined in January or September month.:Select
to_char(hire_date,mon) month, count(*) from
employee group by to_char(hire_date,mon) having
to_char(hire_date,mon) in (jan,sep)
30. How many employees who are joined in 1985: Select to_char(hire_date,yyyy) Year,
count(*) from employee group by to_char(hire_date,yyyy) having
to_char(hire_date,yyyy)=1985
31. How many employees joined each month in 1985. Select
to_char(hire_date,yyyy)Year, to_char(hire_date,mon)
Month, count(*) No. of employees from employee where

to_char(hire_date,yyyy)=1985 group by
to_char(hire_date,yyyy),to_char(hire_date,mon)
32. How many employees who are joined in March 1985.
Select to_char(hire_date,yyyy)Year, to_char(hire_date,mon)
Month, count(*) No. of employees from employee where
to_char(hire_date,yyyy)=1985 and to_char(hire_date,mon)=mar
group by to_char(hire_date,yyyy),to_char(hire_date,mon)
33. Which is the department id, having greater than or equal to 3
Select department_id, count(*) No. of employees from
employee where to_char(hire_date,yyyy)=1985 and
to_char(hire_date,mon)=apr group by to_char(hire_date,yyyy),
to_char(hire_date,mon), department_id having count(*)&gt=3
SubQueries
34. Display the employee who got the maximum salary. : Select * from employee where
salary=(select max(salary)
from employee)
35. Display the employees who are working in Sales department: Select * from
employee where department_id IN (select
department_id from department where name=SALES)
36. Display the employees who are working as Clerk.:
Select * from employee where job_id in (select job_id from
job where function=CLERK
37. Display the employees who are working in New York
Select * from employee where department_id=(select
department_id from department where location_id=(select location_id
from location where regional_group=New York))
38. Find out no.of employees working in Sales department.
Select * from employee where department_id=(select
department_id from department where name=SALES group by
department_id)
39. Update the employees salaries, who are working as Clerk on the basis
of 10%.
Update employee set salary=salary*10/100 wehre job_id=
(select job_id from job where function=CLERK)
40. Delete the employees who are working in accounting department. :delete from
employee where department_id=(select
department_id from department where name=ACCOUNTING)
41. Display the second highest salary drawing employee details.
41.:Select * from employee where salary=(select max(salary)
from employee where salary &lt(select max(salary) from employee))
42. Display the Nth highest salary drawing employee details .:Select distinct e.salary
from employee where &amp no1=(select count(distinct salary) from employee where
sal&gte.salary)
SubQuery
operators: (ALL,ANY,SOME,EXISTS)
43. List out the employees who earn more than every employee in
department 30: Select * from employee where salary &gt all (Select salary

from employee where department_id=30)


44. List out the employees who earn more than the lowest salary in
department 30.:Select * from employee where salary &gt any (Select salary
from employee where department_id=30)
45. Find out whose department has not employees.:Select employee_id, last_name,
department_id from employee where not exists (select department_id from department
d where d.department_id=e.department_id)
46. Find out which department does not have any employees.:Select name from
department d where not exists (select
last_name from employee e where d.department_id=e.department_id)
CoRelated
Sub Queries:
47.Find out the employees who earn greater than the average salary for their
department. :Select employee_id, last_name, salary, department_id from
employee e where salary &gt (select avg(salary) from employee where
department_id=e.department_id)
Joins
Simple join
48.List our employees with their department names
48.:Select employee_id, last_name, name from employee e,
department d where e.department_id=d.department_id
49.Display employees with their designations (jobs)
49.:Select employee_id, last_name, function from employee e, job
j where e.job_id=j.job_id
50.Display the employees with their department name and regional groups.
50.:Select employee_id, last_name, name, regional_group from
employee e, department d, location l where
e.department_id=d.department_id and d.location_id=l.location_id
51.How many employees who are working in different departments and
display with department name.
51.:Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name
51.How many employees who are working in different departments and
display with department name.
52.How many employees who are working in sales department.
52.:Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having name=SALES
53.Which is the department having greater than or equal to 5 employees
and display the department names in ascending order.
53.:Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having count
(*)&gt=5 order by name
54.How many jobs in the organization with designations.
54.:Select function, count(*) from employee e, job j where
j.job_id=e.job_id group by function
55.How many employees working in New York.

55.:Select regional_group, count(*) from employee e, department


d, location l where e.department_id=d.department_id and
d.location_id=l.location_id and regional_group=NEW YORK group by
regional_group
Non Equi Join:
56.Display employee details with salary grades.
56.:Select employee_id, last_name, grade_id from employee e,
salary_grade s where salary between lower_bound and upper_bound
order by last_name
57.List out the no. of employees on grade wise.
57.:Select grade_id, count(*) from employee e, salary_grade s
where salary between lower_bound and upper_bound group by grade_id
order by grade_id desc
58.Display the employ salary grades and no. of employees between
2000 to 5000 range of salary.
58.:Select grade_id, count(*) from employee e, salary_grade s
where salary between lower_bound and upper_bound and
lower_bound&gt=2000 and lower_bound&lt=5000 group by grade_id
order by grade_id desc
Self Join:
59.Display the employee details with their manager names.
59.:Select e.last_name emp_name, m.last_name, mgr_name from
employee e, employee m where e.manager_id=m.employee_id
60.Display the employee details who earn more than their managers
salaries.
60.:Select e.last_name emp_name, e.salary emp_salary,
m.last_name, mgr_name, m.salary mgr_salary from employee e,
employee m where e.manager_id=m.employee_id and m.salary
61.Show the no. of employees working under every manager.
61.:Select m.manager_id, count(*) from employee e, employee m
where e.employee_id=m.manager_id group by m.manager_id
Outer Join:
61.Display employee details with all departments.
Select last_name, d.department_id, d.name from employee e,
department d where e.department_id(+)=d.department_id
62.Display all employees in sales or operation departments.
Select last_name, d.department_id, d.name from employee e,
department d where e.department_id(+)=d.department_id and
d.department_idin (select department_id from department where name
IN (SALES,OPERATIONS))
Set Operators:

63.List out the distinct jobs in Sales and Accounting Departments.


Select function from job where job_id in (Select job_id from
employee where department_id=(select department_id from department
where name=SALES)) union Select function from job where job_id in
(Select job_id from employee where department_id=(select
department_id from department where name=ACCOUNTING))
64.List out the ALL jobs in Sales and Accounting Departments.
Select function from job where job_id in (Select job_id from
employee where department_id=(select department_id from department
where name=SALES)) union all Select function from job where job_id
in (Select job_id from employee where department_id=(select
department_id from department where name=ACCOUNTING))
65.List out the common jobs in Research and Accounting Departments in
ascending order.
Select function from job where job_id in (Select job_id from
employee where department_id=(select department_id from department
where name=RESEARCH)) intersect Select function from job where
job_id in (Select job_id from employee where department_id=(select
department_id from department where name=ACCOUNTING)) order by Function

QTP scripts :
1.Suppose I want to do DP for licindia.com where I need to click on the login button.
Here the hierarchy captured through Object spy shows as
Browser->frame->webTable->webTable->webTable->webTable->Button
In this case how should be the DP for clicking on the button?
Ans:
Beginners will feel difficult when writing descriptive programming.
Here is an example how to write descriptive programming when there are many objects
in an object hierarchy.
The basic hierarchy of an object is Browser--> Page --> Object
Some times when you spy on object it shows Browser--> Page -->WebTable-> WebTable-->WebTable-->Object
But in DP you can ignore webtables in the hierarchy and consider Browser--> Page -->
Object.
When the hierarchy is like Browser--> Page -->Frame-->WebTable--> WebTable->WebTable-->Object
Then consider Browser--> Page -->Frame-->Object
A Simple Technique to identify how to write DP when you have confusion in
hierarchy level
1. Add that object to Object Repository

2.
3.

Identify the hierarchy in OR


Follow the same hierarchy for writing DP

2. Import XLSX Sheet to QTP Datatable


Lot of people are facing problem with one of the major limitation of QTP. That is
importing data from XLSX extension files. But using Excel Object Model we can
overcome this problem.
The below function will import the data from XLSX file to QTP specified data sheet.
1.
Function ImportSheetFromXLSX(dFileName,dSourceSheetName,dDestin
ationSheetName)
2.
3.
Dim ExcelApp
4.
Dim ExcelFile
5.
Dim ExcelSheet
6.
Dim sRowCount
7.
Dim sColumnCount
8.
Dim sRowIndex
9.
Dim sColumnIndex
10.
Dim sColumnValue
11.
12.
Set ExcelApp=CreateObject("Excel.Application")
13.
Set ExcelFile=ExcelApp.WorkBooks.Open (dFileName)
14.
Set ExcelSheet = ExcelApp.WorkSheets(dSourceSheetName)
15.
16.
Set qSheet=DataTable.GetSheet(dDestinationSheetName)
17.
18.
sColumnCount= ExcelSheet.UsedRange.Columns.Count
19.
sRowCount= ExcelSheet.UsedRange.rows.count
20.
21.
For sColumnIndex=1 to sColumnCount
22.
23.
sColumnValue=ExcelSheet.Cells(1,sColumnIndex)
24.
sColumnValue=Replace(sColumnValue," ","_")
25.
26.
If sColumnValue="" Then
27.
sColumnValue="NoColumn"&sColumnIndex
28.
End If
29.
30.
Set qColumn=qSheet.AddParameter (sColumnValue,"")
31.
32.
For sRowIndex=2 to sRowCount
33.
sRowValue=ExcelSheet.Cells(sRowIndex,sColumnIndex)
34.
qColumn.ValueByRow(sRowIndex-1)=sRowValue
35.
Next
36.
37.
Next

38.
Set ImportSheetFromXLSX=qSheet
39.
ExcelFile.Close
40.
ExcelApp.Quit
41.
End Function
42.
'*************************************************************************
*******************************
There is also another way of overwriting Datatable object to import XLSX files. This is
useful for the projects which are already used Datatable.ImportSheet in lot many places
and now they want to enable XLSX support without modifying QTP script. Below is the
example on how to over write datatable object with newly created class. If you use
below code you need to update all existing QTP datatable object methods and
properties.
1.
EnableXLSXsupport()
2.
DataTable.ImportSheet "C:\Users\sudhakar\Desktop\Blog Data\test.xlsx
","Sheet2","Action1"
3.
4.
'*************************************************************************
*******************************
5.
Function EnableXLSXsupport()
6.
7.
ExecuteGlobal "Dim QTPDataTable"
8.
9.
Set QTPDataTable=Datatable
10.
ExecuteGlobal "Dim Datatable"
11.
12.
Set Datatable=New CustomDatatable
13.
14.
End Function
15.
'*************************************************************************
*******************************
16.
Class CustomDatatable
17.
18.
Function ImportSheet(dFileName,dSourceSheetName,dDestinationSheet
Name)
19.
20.
Dim ExcelApp
21.
Dim ExcelFile
22.
Dim ExcelSheet
23.
Dim sRowCount
24.
Dim sColumnCount
25.
Dim sRowIndex
26.
Dim sColumnIndex
27.
Dim sColumnValue
28.
29.
Set ExcelApp=CreateObject("Excel.Application")
30.
Set ExcelFile=ExcelApp.WorkBooks.Open (dFileName)
31.
Set ExcelSheet = ExcelApp.WorkSheets(dSourceSheetName)

32.
33.
Set qSheet=QTPDataTable.GetSheet(dDestinationSheetName)
34.
35.
sColumnCount= ExcelSheet.UsedRange.Columns.Count
36.
sRowCount= ExcelSheet.UsedRange.rows.count
37.
38.
For sColumnIndex=1 to sColumnCount
39.
40.
sColumnValue=ExcelSheet.Cells(1,sColumnIndex)
41.
sColumnValue=Replace(sColumnValue," ","_")
42.
43.
If sColumnValue="" Then
44.
sColumnValue="NoColumn"&sColumnIndex
45.
End If
46.
47.
Set qColumn=qSheet.AddParameter (sColumnValue,"")
48.
49.
For sRowIndex=2 to sRowCount
50.
sRowValue=ExcelSheet.Cells(sRowIndex,sColumnIndex)
51.
qColumn.ValueByRow(sRowIndex-1)=sRowValue
52.
Next
53.
54.
Next
55.
'Set Datatable=QTPDataTable
56.
ExcelFile.Close
57.
ExcelApp.Quit
58.
'Set QTPDataTable=Nothing
59.
End Function
60.
'********************************************************************
61.
Function AddSheet(shtName)
62.
Set AddSheet=QTPDataTable.AddSheet(shtName)
63.
End Function
64.
'********************************************************************
65.
End Class
66.
'*************************************************************************
*******************************
If you uncomment the Set Datatable=QTPDatatable and Set QTPDatatable =Nothing then
this function only works for once. When ever you want to import XLSX sheet then you
need to call EnableXLSXsupport() before you use import sheet. This way is for the
experts who can handle overwriting of reserved objects. Do remember that If you have
not uncommented, the existing datatable methods will not work and you need to define
each method in customdatatable class in order to work. You can observe the "AddSheet"
method in the above class example.
3. All About validation of Editbox : 1 Verify Maximum length
Ans
Basic Editbox Testing Checklist:-

1.Maximum Length
2.Characters Acceptance
Alpha Characters Only
Numeric Characters Only
Alpha Numeric Characters Only
Alpha Numeric Custom Characters
3.Clipboard Text Acceptance
4.Enable / Disable
5.Text Encryption
To understand this post the reader should already know about

String Function in VBScript

GetROProperty Method in QTP

SendKeys Method in WSH Scripting

1. Maximum Length Validation


Identifying max length is possible by using a property called max length. But its a little
tricky if we want to test by entering the maximum number of characters. Suppose a
textbox support 7 characters. In this case we have to make a try, to enter 8 characters. If
we try to enter using set method QTP pops up an error saying The parameter is
incorrect.. In this case we have to for sendkeys method from wsh scripting. Using this
we can replicate manual typing.
Automation Testing is Not like Automating the Application Functionalities. Its
should replicate the exact Manual Actions.
'********************************************************************************
**
1.
Function ValidateTextboxMaxLength(oEditObject,oMaxLen)
2.
3.
Dim wsh
4.
Dim oMaxStr
5.
Dim iValue
6.
7.
set wsh=CreateObject("wscript.shell")
8.
9.
oMaxStr=string(oMaxLen+1,"s")
10.
oEditObject.Set ""
11.
oEditObject.Click
12.
wait(1)
13.
wsh.SendKeys oMaxStr
14.
iValue=oEditObject.GetROProperty("value")
15.
16.
If len(iValue)=oMaxLen then
17.
Reporter.ReportEvent micPass,"Textbox Max Length Validation","Tex
tbox support a Maximum of "& oMaxLength&" Characters"

18.
else
19.
Reporter.ReportEvent micFail,"Textbox Max Length Validation","Text
box support more than "& oMaxLength&"Characters"
20.
End If
21.
Set wsh= nothing
22.
23.
End Function
24.
25.
'*************************************************************************
*********
26.
27.
Calling the Function
28.
29.
set EditObj=Browser("").Page("").WebEdit("")
30.
ValidateTextboxMaxLength EditObj
31.
32.
'OR
33.
34.
RegisterUserFunc "WebEdit","ValidateTextboxMaxLength,"ValidateTextb
oxMaxLength
35.
36.
Browser("").Page("").WebEdit("").ValidateTextboxMaxLength
37.
38.
UnregisterUserFunc "WebEdit","ValidateTextboxMaxLength"
This article is the continuation of my previous post All about Validation of Editbox
Part-1. This will discuss about edit box character acceptance.
Usually there are 3 text character types used to enter in edit box. Sometimes it can be a
combination from these three types.
1.

Alphabetic

2.

Numeric

3.

Special characters

When you check the character acceptance for an edit box using QTP, the edit box will
always accept all the values which are coming from QTP. Even though if that edit box is
developed to enter only alphabetic or only numeric or only special characters. But when
anyuser enters the value it accepts only the values for which it is developed. As I said
before Automation Testing is Not like Automating the Application Functionalities. Its
should Replicate the Exact Manual Actions. So to replicate exact manual actions we have
to use SendKeys method in WSH.
The below function is useful in such conditions
1.
2.
3.

Function ValidateCharacterAcceptance(oEditObject,oTypeofEditBox)
'Variable Declaration

4.
Dim wsh
5.
Dim oTypingText
6.
Dim oVisibleText
7.
8.
'Assign a text value to the variable which is having all value types
9.
oTypingText="SudhakarKakunuri1234@!#$"
10.
11.
'clear the values of edit box and focus on it by clicking
12.
oEditObject.Set ""
13.
oEditObject.Click
14.
'Wait is to clear some disturbance
15.
wait(1)
16.
17.
'Create wscript object
18.
set wsh=CreateObject("wscript.shell")
19.
20.
'Send text using sendkeys method
21.
wsh.SendKeys oTypingText
22.
23.
'Wait is to clear some disturbance
24.
wait(1)
25.
26.
'Get the visible text of the edit box
27.
oVisibleText=oEditObject.GetROProperty("value")
28.
29.
'User can enter any type of text. But editbox accepts only the text which it
is meant for.
30.
'The below condition check the visible text based on the text type.
31.
'If the type of visible text doesnot match the type of the edit box then the c
ondition fails
32.
33.
Select Case lcase(oTypeofEditBox)
34.
35.
Case "alphabetic"
36.
37.
If oVisibleText="SudhakarKakunuri" then
38.
Reporter.ReportEvent micPass,"Check Alphabetic Character Acceptance",
"Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
39.
Else
40.
Reporter.ReportEvent micFail,"Check Alphabetic Character Acceptance", "
Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
41.
End If
42.
43.
Case "numeric"
44.
45.
If oVisibleText="1234" then
46.
Reporter.ReportEvent micPass,"Check Numeric Character Acceptance", "T
yped Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
47.
Else

48.
Reporter.ReportEvent micFail,"Check Numeric Character Acceptance", "T
yped Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
49.
End If
50.
Case "alphanumeric"
51.
52.
If oVisibleText="SudhakarKakunuri1234" then
53.
Reporter.ReportEvent micPass,"Check AlphaNumeric Character Acceptan
ce", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
54.
Else
55.
Reporter.ReportEvent micFail,"Check AlphaNumeric Character Acceptanc
e", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
56.
End If
57.
58.
Case "alphanumericspecial"
59.
60.
If oVisibleText=oTypingText then
61.
Reporter.ReportEvent micPass,"Check AlphaNumericSpecial Character Ac
ceptance", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleT
ext
62.
Else
63.
Reporter.ReportEvent micFail,"Check AlphaNumericSpecial Character Acc
eptance", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleTe
xt
64.
End If
65.
End Select
66.
67.
Set wsh= nothing
68.
End Function
69.
70.
'Calling the Function
71.
Set oEditObject=Browser("").Page("").WebEdit("")
72.
ValidateCharacterAcceptance oEditObject,"alphanumericspecial"
Vbscript Samples
In lot of places I have used print statement. This will work only in QTP. If you
want to execute these samples using .vbs, just replace print with msgbox.
1.
##
2.
##
3.
4.
5.
##
6.
##
7.
8.

'##################################################
'##################################################
'1 Print Hello World
Print "Hello World"
'##################################################
'##################################################
'2 Find whether given number is a odd number
Dim oNumber

9.
10.
11.
12.
13.
14.
15.
16.
##
17.
##
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
##
35.
##
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
##
50.
##
51.

oNumber=4
If oNumber mod 2 <>0 Then
Print "The Number "& oNumber &" is an Odd Number"
else
Print "The Number "& oNumber &" is not an Odd Number"
End If
'##################################################
'##################################################
'3 Print odd numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=10
RangeEnd=20
For iCounter=RangeStart to RangeEnd
If iCounter mod 2 <>0 Then
Print oNumber
End If
Next
'##################################################
'##################################################
'4 Find the factorial of a given number
Dim oNumber
Dim iCounter
Dim fValue
oNumber=6
fValue=1
For iCounter=oNumber to 1 step-1
fValue=fValue*iCounter
Next
print fValue
'##################################################
'##################################################
'5 Find the factors of a given number

52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
##
64.
##
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
##
87.
##
88.
89.
90.
91.
92.
93.
94.
95.
96.

Dim oNumber
Dim iCounter
oNumber=10
For iCounter=1 to oNumber/2
If oNumber mod iCounter=0 Then
print iCounter
End If
Next
print oNumber
'##################################################
'##################################################
'6 Print prime numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=1
RangeEnd=30
For iCounter=RangeStart to RangeEnd
For iCount=2 to round(iCounter/2)
If iCounter mod iCount=0 Then
Exit for
End If
Next
If iCount=round(iCounter/2)+1 or iCounter=1 Then
print iCounter
End If
Next
'##################################################
'##################################################
'7 Swap 2 numbers with out a temporary variable
Dim oNum1
Dim oNum2
oNum1=1055
oNum2=155
oNum1=oNum1-oNum2

97.
oNum2=oNum1+oNum2
98.
oNum1=oNum2-oNum1
99.
print oNum1
100. print oNum2
101. '##################################################
##
102. '##################################################
##
103. '8 Write a program to Perform specified Arithmetic Operation on two gi
ven numbers
104. Dim oNum1
105. Dim oNum2
106. Dim oValue
107.
108. oNum1=10
109. oNum2=20
110.
111. OperationtoPerform="div"
112.
113. Select Case lcase(OperationtoPerform)
114.
115.
Case "add"
116.
oValue=oNum1+oNum2
117.
Case "sub"
118.
oValue=oNum1-oNum2
119.
Case "mul"
120.
oValue=oNum1*oNum2
121.
Case "div"
122.
oValue=oNum1/ oNum2
123. End Select
124. print oValue
125. '##################################################
##
126. '##################################################
##
127. '9 Find the length of a given string
128. Dim oStr
129. Dim oLength
130. oStr="sudhakar"
131. oLength=len(oStr)
132. print oLength
133. '##################################################
##
134. '##################################################
##
135. '10 Reverse given string
136. Dim oStr
137. Dim oLength
138. Dim oChar

139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
##
149.
##
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
##
171.
##
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
##

Dim iCounter
oStr="sudhakar"
oLength=len(oStr)
For iCounter=oLength to 1 step-1
oChar=oChar&mid(oStr,iCounter,1)
Next
print oChar
'##################################################
'##################################################
'11 Find how many alpha characters present in a string.
Dim oStr
Dim oLength
Dim oChar
Dim iCounter
oStr="su1h2kar"
oLength=len(oStr)
oAlphacounter=0
For iCounter=1 to oLength
If not isnumeric (mid(oStr,iCounter,1)) then
oAlphacounter=oAlphacounter+1
End if
Next
print oAlphacounter
'##################################################
'##################################################
'12 Find occurrences of a specific character in a string
Dim oStr
Dim oArray
Dim ochr
oStr="sudhakar"
ochr="a"
oArray=split(oStr,ochr)
print ubound(oArray)
'##################################################

183. '##################################################
##
184. '13 Replace space with tab in between the words of a string.
185.
186. Dim oStr
187. Dim fStr
188.
189. oStr="Quick Test Professional"
190.
191. fStr=replace(oStr," ",vbtab)
192. print fStr
193.
194. '##################################################
##
195. '##################################################
##
196. '14 Write a program to return ASCII value of a given character
197.
198. Dim ochr
199. Dim aVal
200.
201. ochr="A"
202.
203. aVal=asc(ochr)
204. print aVal
205.
206. '##################################################
##
207. '##################################################
##
208. '15 Write a program to return character corresponding to the given ASCI
I value
209.
210. Dim ochr
211. Dim aVal
212.
213. aVal=65
214.
215. oChr=chr(aVal)
216. print oChr
217.
218. '##################################################
##
219. '##################################################
##
220. '16 Convert string to Upper Case
221. Dim oStr
222. Dim uStr
223.

224.
225.
226.
227.
228.
##
229.
##
230.
231.
232.
233.
234.
235.
236.
237.
238.
##
239.
##
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
##
255.
##
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.

oStr="QuickTest Professional"
uStr=ucase(oStr)
print uStr
'##################################################
'##################################################
'17 Convert string to lower case
Dim oStr
Dim lStr
oStr="QuickTest Professional"
lStr=lcase(oStr)
print lStr
'##################################################
'##################################################
'18 Write a program to Replace a word in a string with another word
Dim oStr
Dim oWord1
Dim oWord2
Dim fStr
oStr="Mercury Quick Test Professional"
oWord1="Mercury"
oWord2="HP"
fStr=replace(oStr,oWord1,oWord2)
print fStr
'##################################################
'##################################################
'19 Check whether the string is a POLYNDROM
Dim oStr
oStr="bob"
fStr=StrReverse(oStr)
If oStr=fStr Then
Print "The Given String "&oStr&" is a Palindrome"
else
Print "The Given String "&oStr&" is not a Palindrome"
End If

267.
##
268.
##
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
##
281.
##
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
##
292.
##
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.

'##################################################
'##################################################
'20 Verify whether given two strings are equal
Dim oStr1
Dim ostr2
oStr1="qtp"
oStr2="qtp"
If oStr1=oStr2 Then
Print "The Given Strings are Equal"
else
Print "The Given Strings are not Equal"
End If
'##################################################
'##################################################
'21 Print all values from an Array
Dim oArray
Dim oCounter
oArray=array(1,2,3,4,"qtp","Testing")
For oCounter=lbound(oArray) to ubound(oArray)
print oArray(oCounter)
Next
'##################################################
'##################################################
'22 Sort Array elements
Dim oArray
Dim oCounter1
Dim oCounter2
Dim tmp
oArray=array(8,3,4,2,7,1,6,9,5,0)
For oCounter1=lbound(oArray) to ubound(oArray)
For oCounter2=lbound(oArray) to ubound(oArray)-1
If oArray(oCounter2)>oArray(oCounter2+1) Then
tmp=oArray(oCounter2)
oArray(oCounter2)=oArray(oCounter2+1)
oArray(oCounter2+1)=tmp
End If

310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
##
320.
##
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
##
341.
##
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.

Next
Next
For oCounter1=lbound(oArray) to ubound(oArray)
print oArray(oCounter1)
Next
'##################################################
'##################################################
'23 Add two 2X2 matrices
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2
oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)+ oArray2(0,0)
tArray(0,1)=oArray1(0,1)+oArray2(0,1)
tArray(1,0)=oArray1(1,0)+oArray2(1,0)
tArray(1,1)=oArray1(1,1)+oArray2(1,1)
'##################################################
'##################################################
'24 Multiply Two Matrices of size 2X2
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2

355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
##
366.
##
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
##
379.
##
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
##
392.
##
393.
394.
395.
396.
397.

oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)* oArray2(0,0)+ oArray1(0,1)* oArray2(1,0)
tArray(0,1)=oArray1(0,0)* oArray2(0,1)+ oArray1(0,1)* oArray2(1,1)
tArray(1,0)=oArray1(1,0)* oArray2(0,0)+ oArray1(1,1)* oArray2(1,0)
tArray(1,1)=oArray1(1,0)* oArray2(0,1)+ oArray1(1,1)* oArray2(1,1)
'##################################################
'##################################################
'25 Convert a String in to an array
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr)
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'##################################################
'##################################################
'26 Convert a String in to an array using i as delimiter
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr,"i")
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'##################################################
'##################################################
'27 Find number of words in string
Dim oStr
Dim iCounter
oStr="Quick Test Professional"

398. StrArray=split(oStr," ")


399. print "Theere are "&ubound(StrArray)+1&" words in the string"
400.
401. '##################################################
##
402. '##################################################
##
403. '28 Write a program to reverse the words of a given string.
404.
405. Dim oStr
406. Dim iCounter
407. oStr="Quick Test Professional"
408. StrArray=split(oStr," ")
409.
410. For iCounter=0 to ubound(StrArray)
411.
print strreverse(StrArray(iCounter))
412. Next
413.
414. '##################################################
##
415. '##################################################
##
416. '29 Print the data as a Pascal triangle
417. 'The formulae for pascal triangle is nCr=n!/(n-r)!*r!
418.
419. Dim PascalTriangleRows
420. Dim nCr
421. Dim NumCount
422. Dim RowCount
423.
424. PascalTriangleRows = 10
425. For NumCount = 0 To PascalTriangleRows
426.
toPrint= Space(PascalTriangleRows - NumCount)
427.
For RowCount = 0 To NumCount
428.
If (NumCount = RowCount) Then
429.
nCr = 1
430.
Else
431.
nCr = Factorial(NumCount) / (Factorial(NumCount RowCount) * Factorial(RowCount))
432.
End If
433.
toPrint=toPrint&nCr&" "
434.
Next
435.
print toPrint
436. Next
437.
438.
439. Function Factorial(num)
440.
Dim iCounter
441.
Factorial = 1

442.
443.
444.
445.
446.
447.
448.
##
449.
##
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
##
460.
##
461.
462.
463.
464.
465.
466.
467.
468.
##
469.
##
470.
array
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.

If num <> 0 Then


For iCounter = 2 To num
Factorial = Factorial * iCounter
Next
End If
End Function
'##################################################
'##################################################
'30 Join elements of an array as a string
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr," ")
print join(StrArray," ")
'##################################################
'##################################################
'31 Trim a given string from both sides
Dim oStr
oStr=" QTP "
print trim(oStr)
'##################################################
'##################################################
'32 Write a program to insert 100values and to delete 50 values from an
Dim oArray()
Dim iCounter
ReDim oArray(100)
For iCounter=0 to ubound(oArray)
oArray(iCounter)=iCounter
'Print total 100 Values
print(oArray(iCounter))
Next
print "******************************"
print "******************************"

484.
485.
486.
487.
488.
489.
490.
##
491.
##
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
##
503.
##
504.
505.
506.
507.
508.
509.
510.
##
511.
##
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
##
522.
##
523.
524.

ReDim preserve oArray(50)


For iCounter=0 to ubound(oArray)
'Print Values after deleting 50 values
print(oArray(iCounter))
Next
'##################################################
'##################################################
'33 Write a program to force the declaration of variables
Option explicit ' this keyword will enforce us to declare variables
Dim x
x=10
'Here we get an error because i have not declared y,z
y=20
z=x+y
print z
'##################################################
'##################################################
'34 Write a program to raise an error and print the error number.
On Error Resume Next
Err.Raise 6 ' Raise an overflow error.
print ("Error # " & CStr(Err.Number) & " " & Err.Description)
'##################################################
'##################################################
'35 Finding whether a variable is an Array
Dim oArray()
if isarray(oArray) then
print "the given variable is an array"
else
print "the given variable is not an array"
End if
'##################################################
'##################################################
'36 Write a program to list the Timezone offset from GMT
Dim objWMIService

525. Dim colTimeZone


526. Dim objTimeZone
527.
528. Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=im
personate}!\\.\root\cimv2")
529. Set colTimeZone = objWMIService.ExecQuery("Select * from Win32_Time
Zone")
530.
531. For Each objTimeZone in colTimeZone
532.
print "Offset: "& objTimeZone.Bias
533. Next
534. '##################################################
##
535. '##################################################
##
536. '37 Retrieving Time Zone Information for a Computer
537. Dim objWMIService
538. Dim colTimeZone
539. Dim objTimeZone
540.
541. Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=im
personate}!\\.\root\cimv2")
542. Set colTimeZone = objWMIService.ExecQuery("Select * from Win32_Time
Zone")
543.
544. For Each objItem in colTimeZone
545.
546.
print "Bias: " & objItem.Bias
547.
print "Caption: " & objItem.Caption
548.
print "Daylight Bias: " & objItem.DaylightBias
549.
print "Daylight Day: " & objItem.DaylightDay
550.
print "Daylight Day Of Week: " & objItem.DaylightDayOfWeek
551.
print "Daylight Hour: " & objItem.DaylightHour
552.
print "Daylight Millisecond: " & objItem.DaylightMillisecond
553.
print "Daylight Minute: " & objItem.DaylightMinute
554.
print "Daylight Month: " & objItem.DaylightMonth
555.
print "Daylight Name: " & objItem.DaylightName
556.
print "Daylight Second: " & objItem.DaylightSecond
557.
print "Daylight Year: " & objItem.DaylightYear
558.
print "Description: " & objItem.Description
559.
print "Setting ID: " & objItem.SettingID
560.
print "Standard Bias: " & objItem.StandardBias
561.
print "Standard Day: " & objItem.StandardDay
562.
print "Standard Day Of Week: " & objItem.StandardDayOfWeek
563.
print "Standard Hour: " & objItem.StandardHour
564.
print "Standard Millisecond: " & objItem.StandardMillisecond
565.
print "Standard Minute: " & objItem.StandardMinute
566.
print "Standard Month: " & objItem.StandardMonth
567.
print "Standard Name: " & objItem.StandardName

568.
569.
570.
571.
572.
573.
##
574.
##
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
##
589.
##
590.
591.
592.
593.
##
594.
##
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
##
607.
##
608.

print "Standard Second: " & objItem.StandardSecond


print "Standard Year: " & objItem.StandardYear
Next
'##################################################
'##################################################
'38 Write a program to Convert an expression to a date
Dim StrDate
Dim actualDate
Dim StrTime
Dim actualTime
StrDate = "October 19, 1962" ' Define date.
actualDate = CDate(StrDate) ' Convert to Date data type.
print actualDate
StrTime = "4:35:47 PM"
' Define time.
actualTime = CDate(StrTime) ' Convert to Date data type.
print actualTime
'##################################################
'##################################################
'39 Display current date and Time
print now
'##################################################
'##################################################
'40 Find difference between two dates.
'Date difference in Years
print DateDiff("yyyy","12/31/2002",Date)
'Date difference in Months
print DateDiff("m","12/31/2002",Date)
'Date difference in Days
print DateDiff("d","12/31/2002",Date)
'##################################################
'##################################################
'41 Add time interval to a date

609.
610.
611.
612.
##
613.
##
614.
615.
616.
617.
##
618.
##
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
##
634.
##
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
) then
649.
650.

print DateAdd("m", 1, "31-Jan-95")


'##################################################
'##################################################
'42 Print current day of the week
Print day(date)
'##################################################
'##################################################
'43 Find whether current month is a long month
Dim oCurrentMonth
Dim ocurrentYear
Dim oDaysinMonths
oCurrentMonth = Month(date)
ocurrentYear = Year(date)
oDaysinMonths=Day(DateSerial(ocurrentYear, oCurrentMonth + 1, 0))
print oDaysinMonths&" Days in Current Month"
If oDaysinMonths=31 Then
print "Current Month is a long month"
else
print "Current Month is not a long month"
End If
'##################################################
'##################################################
'44 Find whether given year is a leap year
'1st Method
'The rules for leap year:
'1. Leap Year is divisible by 4 (This is mandotory Rule)
'2. Leap Year is not divisible by 100 (Optional)
'3. Leap Year divisble by 400 (Optional)
Dim oYear
oYear=1996
If ((oYear Mod 4 = 0) And (oYear Mod 100 <> 0) Or (oYear Mod 400 = 0)
print "Year "&oYear&" is a Leap Year"
else

651.
652.
653.
654.
655.
656.
657.
658.
659.
660.
661.
662.
663.
664.
665.
666.
667.
668.
669.
670.
##
671.
##
672.
673.
674.
675.
676.
677.
678.
679.
680.
##
681.
##
682.
683.
684.
685.
686.
687.
688.
689.
690.
691.
692.
693.
##

print "Year "&oYear&" is not a Leap Year"


End If
'45. 2nd Method
' Checking 29 days for February month in specified year
Dim oYear
Dim tmpDate
oYear=1996
tmpDate = "1/31/" & oYear
DaysinFebMonth = DateAdd("m", 1, tmpDate)
If day(DaysinFebMonth )=29 then
print "Year "&oYear&" is a Leap Year"
else
print "Year "&oYear&" is not a Leap Year"
End If
'##################################################
'##################################################
'46 Format Number to specified decimal places
Dim oNum
Dim DecimaPlacestobeFormat
oNum = 3.14159
DecimaPlacestobeFormat=2
print Round(oNum , DecimaPlacestobeFormat)
'##################################################
'##################################################
'47 Write a program to Generate a Random Numbers
'This script will generate random numbers between 10 and 20
Dim rStartRange
Dim rEndRange
rStartRange=10
rEndRange=20
For iCounter=1 to 10
print Int((rEndRange - rStartRange + 1) * Rnd + rStartRange)
Next
'##################################################

694. '##################################################
##
695. '48 Write a program to show difference between Fix and Int
696.
697. 'Both Int and Fix remove the fractional part of number and return the res
ulting integer value.
698. 'The difference between Int and Fix is that if number is negative, Int retur
ns the first negative integer less than or equal to number,
699. 'Whereas Fix returns the first negative integer greater than or equal to nu
mber.
700. 'For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.
701.
702. print Int(99.8) ' Returns 99.
703. print Fix(99.2) ' Returns 99.
704. print Int(-99.8) ' Returns -100.
705. print Fix(-99.8) ' Returns -99.
706. print Int(-99.2) ' Returns -100.
707. print Fix(-99.2) ' Returns -99.
708.
709. '##################################################
##
710. '##################################################
##
711. '49 Write a program to find subtype of a variable
712.
713. Dim oVar
714. Dim oDatatypes
715. oVar="QTP"
716. oVartype=Typename(oVar)
717. print oVartype
718.
719. '##################################################
##
720. '##################################################
##
721. '50 Write a program to print the decimal part of a given number
722. Dim oNum
723. oNum=3.123
724. oDecNum=oNum- int(oNum)
725. print oDecNum
726. '##################################################
##
727. '##################################################
##
9) Using one library function in other library
As we all know that we can automate the Web Applications by using only DOM +
VBScript without having any automation tool. In this process we have to write the

global functions to handle webobjects like links, edit boxes, radio buttons etc.
I have got a requirement to automate an application only by using DOM + VBscript. For
this process I have created all the global functions to handle every web object and
stored all the functions in a library. Find some of the functions here to handle link, Edit,
Radio buttons etc.
This is the plan I thought to Automate the Testcases Using DOM

Develop Global Functions to handle Web Objects

Write scripts by calling global functions (scripts will be stored as VBS files)
I thought of using filesystem object and execute statements to call functions in . But
those are not fully capable for some of the situations. And the next one immediately
came in my mind is Microsoft Script Control.
Using Microsoft Script Control you can call one library functions in another library. For
this you have to follow below steps.

1.

Read and store all the text from source library file using filesystem object

2.

Add the source library code as vbscript in MSScriptControl

3.
Call the functions using MSScriptControl methods
Source Library Code
Dim a
a=20
Function demo ()
MsgBox "QTP Sudhakar"
End Function
Function demo_add (x,y)
demo_add = x+y
End Function
Calling the Functions in other libraries
'Create file system object
Set fso=CreateObject("scripting.filesystemobject")
'Open library file
Set sFile=fso.OpenTextFile("C:\Documents and Settings\sudhakar
kakunuri\Desktop\Script Control\source.vbs")
'Read the complete data from library file
SourceLibraryData=sFile.ReadAll
'close the file
sFile.Close
'Create Script Control Object
Set scrControl=CreateObject("msscriptcontrol.scriptcontrol")
'Specify the language to be controlled
scrControl.Language = "VBScript"

'Add the source library code


scrControl.AddCode(SourceLibraryData)
'Diplay the number of procedures in th source library
MsgBox scrControl.Procedures.Count,,"Total Procedures Count"
'Display value of a variable in source library
Msgbox scrControl.Eval("a"),,"Value of Variable 'a'"
'Executing the function source library function
scrControl.Run "demo"
'Executing the function source library function with parameters
msgbox scrControl.Run("demo_add",10,20),,"demo_add function Result"
10) Verify Data sorting using acending
1.
'##################################################
############
2.
'#################### String Sort ######################
#######
3.
'##################################################
############
4.
5.
'*************************************************************
6.
' Function Name : CheckStringSortAscending
7.
' Parameter : An Array contains list of strings
8.
' Description : This function checks the given list of
9.
' strings are in ascending order
10.
'*************************************************************
11.
12.
Function CheckStringSortAscending(strArray)
13.
14.
Dim aIndex
15.
16.
CheckStringSortAscending=True
17.
18.
For aIndex=0 To UBound(strArray)-1
19.
20.
If StrComp(lCase(strArray(aIndex)),LCase(strArray(aIndex+1)))>0 Then
21.
CheckStringSortAscending=False
22.
Exit Function
23.
End If
24.
Next
25.
26.
End Function
27.
28.
'*************************************************************
29.
'##################################################
###########
30.
'*************************************************************

31.
' Function Name : CheckStringSortDescending
32.
' Parameter : An Array contains list of strings
33.
' Description : This function checks the given list of
34.
' strings are in descending order
35.
'*************************************************************
36.
Function CheckStringSortDescending(strArray)
37.
38.
Dim aIndex
39.
40.
CheckStringSortDescending=True
41.
42.
For aIndex=0 To UBound(strArray)-1
43.
44.
If StrComp(lcase(strArray(aIndex)),lcase(strArray(aIndex+1)))<0 Then
45.
CheckStringSortDescending=False
46.
Exit Function
47.
End If
48.
Next
49.
50.
End Function
51.
52.
'*************************************************************
###########################################################
1.
'#################### Date Sort #######################
########
2.
'##################################################
############
3.
4.
'*************************************************************
5.
' Function Name : CheckDateSortAscending
6.
' Parameter : An Array contains list of Date Values
7.
' Description : This function checks the given list of
8.
' Date values are in ascending order
9.
'*************************************************************
10.
11.
Function CheckDateSortAscending(dtArray)
12.
13.
Dim aIndex
14.
15.
CheckDateSortAscending=True
16.
17.
For aIndex=0 To UBound(dtArray)-1
18.
19.
If DateDiff("d",dtArray(aIndex),dtArray(aIndex+1))<0 Then
20.
CheckDateSortAscending=False
21.
Exit Function
22.
End If
23.

24.
Next
25.
26.
End Function
27.
28.
'*************************************************************
29.
'##################################################
###########
30.
'*************************************************************
31.
' Function Name : CheckDateSortDescending
32.
' Parameter : An Array contains list of Date Values
33.
' Description : This function checks the given list of
34.
' Date values are in Descending order
35.
'*************************************************************
36.
37.
Function CheckDateSortDescending(dtArray)
38.
39.
Dim aIndex
40.
41.
CheckDateSortDescending=True
42.
43.
For aIndex=0 To UBound(dtArray)-1
44.
45.
If DateDiff("d",dtArray(aIndex),dtArray(aIndex+1))>0 Then
46.
CheckDateSortDescending=False
47.
Exit Function
48.
End If
49.
50.
Next
51.
52.
End Function
53.
54.
'*************************************************************
1.
'##################################################
############
2.
'#################### Numeric Sort ####################
########
3.
'##################################################
############
4.
5.
'*************************************************************
6.
' Function Name : CheckNumericSortAscending
7.
' Parameter : An Array contains list of numbers
8.
' Description : This function checks the given list of
9.
' numbers are in Ascending order
10.
'*************************************************************
11.
12.
Function CheckNumericSortAscending(numArray)
13.

14.
Dim aIndex
15.
16.
CheckNumericSortAscending=True
17.
18.
For aIndex=0 To UBound(numArray)-1
19.
20.
If numArray(aIndex)>numArray(aIndex+1) Then
21.
CheckNumericSortAscending=False
22.
Exit Function
23.
End If
24.
Next
25.
26.
End Function
27.
28.
'*************************************************************
29.
'##################################################
###########
30.
'*************************************************************
31.
' Function Name : CheckNumericSortDescending
32.
' Parameter : An Array contains list of numbers
33.
' Description : This function checks the given list of
34.
' numbers are in Descending order
35.
'*************************************************************
36.
37.
Function CheckNumericSortDescending(numArray)
38.
39.
Dim aIndex
40.
41.
CheckNumericSortDescending=True
42.
43.
For aIndex=0 To UBound(numArray)-1
44.
45.
If numArray(aIndex)<numArray(aIndex+1) Then
46.
CheckNumericSortDescending=False
47.
Exit Function
48.
End If
49.
Next
50.
51.
End Function
52.
53.
'*************************************************************
10)Different ways to write a statement
1.
2.
3.
4.
5.

'Different ways to write a statement


'##############################
'#### 1st method ###############
'##############################

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
rch")
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
)
47.
48.
49.
50.
51.
52.

'***Common Method***
'For Web
Browser("Google").Page("Google").WebButton("Google Search").Click
'*******************
'For Windows
Window("Flight Reservation").WinButton("Update Order").Click
'##############################
'#### 2nd method ###############
'##############################
'*** Assigning window object to an object variable***
'For Web
'Assigning Parent Object to a variable
Set oPageObj=Browser("Google").Page("Google")
oPageObj.WebButton("Google Search").Click
'Assigning Complete Object to a variable
Set oBtnObj=Browser("Google").Page("Google").WebButton("Google Sea
oBtn.Click
'*******************
'For Windows
Set wndObject=Window("Flight Reservation")
' Following normal syntax ( click on a button)
wndObject.WinButton("Update Order").Click
'

OR

' Assigning Button object to an object variable


Set btnObject=Window("Flight Reservation").WinButton("Update Order"
' Clicking on button using button object variable
btnObject.Click
'##############################
'#### 3rd method ###############
'##############################

53.
54.
'*** Using With statement***
55.
56.
'For Web
57.
With Browser("Google").Page("Google")
58.
WebButton("Google Search").Click
59.
End With
60.
61.
'*******************
62.
63.
'For Windows
64.
65.
With Window("Flight Reservation")
66.
.WinButton("Update Order").click
67.
End with
68.
69.
'##############################
70.
'#### 4th method ###############
71.
'##############################
72.
73.
'***Descriptive programming (Static Description)***
74.
75.
'For Web
76.
77.
Browser("name:=Google").Page("title:=Google").WebButton("name:=Goo
gle Search").Click
78.
79.
'*******************
80.
81.
'For Windows
82.
83.
Window("text:=Flight Reservation").WinButton("text:=&Update Order").
Click
84.
85.
'##############################
86.
'#### 5th method ###############
87.
'##############################
88.
89.
'***Descriptive programming (Dynamic Description)***
90.
91.
'For Web
92.
93.
Set oDes=Description.Create
94.
' assigning description to the description object
95.
oDes("micclass").value="WebButton"
96.
oDes("name").value="Google Search"
97.
' clicking on button using the created description object
98.
Browser("name:=Google").Page("title:=Google").WebButton(oDes).click
99.

100. '*******************
101.
102. 'For Windows
103.
104. Set oDes=Description.Create
105. ' assigning description to the description object
106. oDes("nativeclass").value="Button"
107. oDes("text").value="&Update Order"
108. ' clicking on button using the created description object
109. Window("text:=Flight Reservation").winbutton(oDes).click
110.
111. '##############################
112. '#### 6th method ###############
113. '##############################
114.
115. '***Using Descriptive Programming Child Object Method***
116.
117. 'For Web
118.
119. ' creating a description object
120. Set oDes=Description.Create
121. ' assigning description to the description object
122. oDes("micclass").value="WebButton"
123.
124. ' Flitering the objects
125. set btnObjList=Browser("name:=Google").Page("title:=Google").ChildObj
ects(oDes)
126.
127. For objIndex=0 to btnObjList.count-1
128.
' Get property value from object
129.
propVal=btnObjList(objIndex).getroproperty("name")
130.
131.
' Compare property value
132.
If propVal="Google Search" Then
133.
' Click on identified object
134.
btnObjList(objIndex).click
135.
' Exit For loop after clicking on the button
136.
Exit for
137.
End If
138. Next
139.
140. '*******************
141.
142. 'For Windows
143.
144. ' creating a description object
145. Set oDes=Description.Create
146. oDes("nativeclass").value="Button"
147.

148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
ion***
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.

' Flitering the objects


set btnObjList=Window("text:=Flight Reservation").ChildObjects(oDes)
For objIndex=0 to btnObjList.count-1
' Get property value from object
propVal=btnObjList(objIndex).getroproperty("text")
' Compare property value
If propVal="&Update Order" Then
' Click on identified object
btnObjList(objIndex).click
' Exit For loop after clicking on the button
Exit for
End If
Next
'##############################
'#### 7th method ###############
'##############################
'***By Storing Description in to Variable and replacing them with descript
'For Web
' Assigning Parent object description to constants
Public const gBrowser="name:=Google"
Public const gPage="title:=Google"
' Assigning Button object description to a constant
Public const btnSearch="name:=Google Search"
' Click on a button using description constants
Browser(gBrowser).Page(gPage).WebButton(btnSearch).Click
'*******************
'For Windows
' Assigning window object description to a constant
Public const wndFlight="text:=Flight Reservation"
' Assigning Button object description to a constant
Public const btnUpdate="text:=&Update Order"
' Click on a button using description constants
Window(wndFlight).winbutton(btnUpdate).click
'##############################
'#### 8th method ###############

196. '##############################
197.
198. '***By Using DOM Methods***
199.
200. ' Assigning Parent object description to constants
201. Public const gBrowser="name:=Google"
202. Public const gPage="title:=Google"
203.
204. 'Using GetElementsByName Method
205. 'Get Elements List
206. Set ElemLst=Browser(gBrowser).Page(gPage).object.getelementsbynam
e("Google Search")
207.
208. For each elem in ElemLst
209.
'Fliter Elements by Tag Name & Type
210.
If elem.tagName="INPUT" or elem.tagName="BUTTON" Then
211.
If lcase(elem.type)="button" Or lcase(elem.type)="submit" Then
212.
'Click on identified element
213.
Elem.click
214.
End If
215.
End If
216.
217. Next
218.
219. '*******************
220.
221. 'Using GetElementById Method (For this method object must have Id)
222. Browser(gBrowser).Page(gPage).object.getElementById("Google Search"
).click
223.
224. '*******************
225.
226. 'Using GetElementsByTagName Method
227. 'If the button has input tag
228. Set ElemLst=Browser(gBrowser).Page(gPage).object.getelementsbyTagN
ame("INPUT")
229.
230.
For each elem in ElemLst
231.
232.
If elem.type="BUTTON" Or elem.type="SUBMIT" Then
233.
If elem.value="Google Search" Then
234.
elem.click
235.
Exit For
236.
End if
237.
End If
238.
Next
239.
240. 'If the button has Button tag

241. Set ElemLst=Browser(gBrowser).Page(gPage).object.getelementsbyTagN


ame("BUTTON")
242.
243.
For each elem in ElemLst
244.
If elem.type="BUTTON" Or elem.type="SUBMIT" Then
245.
If elem.value="Google Search" Then
246.
elem.click
247.
Exit For
248.
End if
249.
End If
250.
Next

Create excel file and enter some data save it


###############################################
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.

'Create excel file and enter some data save it


'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Add New Workbook
Set workbooks=excel.Workbooks.Add()
'Set the value in First row first column
excel.Cells(1,1).value="testing"
'Save Work Book
workbooks.saveas"D:\excel.xls"
'Close Work Book
workbooks.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set workbooks=Nothing
Set excel=Nothing
Reading Values from a Specific excel Sheet

view plainprint?
1.

'###############################################

2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.

' Reading Values from a Specific excel Sheet


'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open the Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get the Control on Specific Sheet
Set worksheet1=excel.Worksheets.Item("Sheet1")
' Display the Values
Msgbox worksheet1.cells(1,1).value
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Deleting Rows from Excel Sheet

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

'###############################################
' Deleting Rows from Excel Sheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open the Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get the Control on Specific Sheet
Set worksheet1=excel.Worksheets.Item("Sheet1")
'Delete Row1

18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

worksheet1.Rows("1:1").delete
'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Add and Delete ExcelSheet

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

'###############################################
' Add and Delete ExcelSheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Existing Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Add New Sheet
Set newsheet=workbook.sheets.Add
'Assign a Name
newsheet.name="raj"
'Delete Sheet
Set delsheet=workbook.Sheets("raj")
delsheet.delete
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables

31.
32.
33.
34.

Set newsheet=Nothing
Set delsheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Copy an Excel Sheet of one Excel File to another Excel File

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.

'###############################################
' Copy an Excel Sheet of one Excel File to another Excel File
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open First Excel File
Set workbook1=excel.Workbooks.Open("D:\excel1.xls")
'Open Second Excel File
Set workbook2=excel.Workbooks.Open("D:\excel2.xls")
'Copy data from first excel file sheet
workbook1.Worksheets("raj").usedrange.copy
'Paste Data to Second Excel File Sheet
workbook2.Worksheets("Sheet1").pastespecial
'Save Workbooks
workbook1.Save
workbook2.Save
'Close Workbooks
workbook1.Close
workbook2.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set workbook1=Nothing
Set workbook2=Nothing
Set excel=Nothing
Comapre Two Excel Sheets Cell By Cell for a specific Range

view plainprint?

1.
'###############################################
2.
' Comapre Two Excel Sheets Cell By Cell for a specific Range
3.
'###############################################
4.
5.
'Create Excel Object
6.
Set excel=createobject("excel.application")
7.
8.
'Make it Visible
9.
excel.Visible=True
10.
11.
'Open Excel File
12.
Set workbook=excel.Workbooks.Open("D:\excel.xls")
13.
14.
'Get Control on First Sheet
15.
Set sheet1=excel.Worksheets.Item("Sheet1")
16.
17.
'Get Control on Second Sheet
18.
Set sheet2=excel.Worksheets.Item("Sheet2")
19.
20.
'Give the specific range for Comparision
21.
CompareRangeStartRow=1
22.
NoofRows2Compare=4
23.
CompareRangeStartColumn=1
24.
NoofColumns2Compare=4
25.
26.
'Loop through Rows
27.
For r=CompareRangeStartRow to(CompareRangeStartRow+(NoofRows2
Compare-1))
28.
29.
'Loop through columns
30.
For c=CompareRangeStartColumn to(CompareRangeStartColumn+(Noof
Columns2Compare-1))
31.
32.
'Get Value from the First Sheet
33.
value1=Trim(sheet1.cells(r,c))
34.
'Get Value from the Second Sheet
35.
value2=Trim(sheet2.cells(r,c))
36.
37.
'Compare Values
38.
If value1<>value2 Then
39.
40.
' If Values are not matched make the text with Red color
41.
sheet2.cells(r,c).font.color=vbred
42.
43.
End If
44.
45.
Next
46.
47.
Next

48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.

'Save workbook
workbook.Save
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set sheet1=Nothing
Set sheet2=Nothing
Set workbook=Nothing
Set excel=Nothing
Reading complete data from excel file

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

'###############################################
' Reading complete data from excel file
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("raj")
'Get the count of used columns
ColumnCount=worksheet.usedrange.columns.count
'Get the count of used Rows
RowCount=worksheet.usedrange.rows.count
'Get the Starting used Row and column
top=worksheet.usedrange.row
lft=worksheet.usedrange.column
'Get cell object to get the values cell by cell
Set cells=worksheet.cells
'Loop through Rows

31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.

For row=top to (RowCount-1)


rdata=""
'Loop through Columns
For col=lft to ColumnCount-1
'Get Cell Value
word=cells(row,col).value
'concatenate all row cell values into one variable
rdata=rdata&vbtab&word
Next
'Print complete Row Cell Values
print rdata
Next
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Read complete data from an Excel Sheet content

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

'###############################################
' Read complete data from an Excel Sheet content
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.open("D:\excel.xlsx")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("Sheet1")
'Get Used Row and Column Count
rc=worksheet.usedrange.rows.count
cc=worksheet.usedrange.columns.count

21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.

'Loop through Rows


For Row=1 to rc
'Loop through Columns
For Column=1 to cc
'Get Cell Data
RowData=RowData&worksheet.cells(Row,Column)&vbtab
Next
RowData=RowData&vbcrlf
Next
'Display complete Data
msgbox RowData
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Assign Colours to Excel Sheet Cells, Rows

view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.

'###############################################
' Assign Colours to Excel Sheet Cells, Rows
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Add a New work book
Set workbook=excel.workbooks.add()
'Get the Excel Sheet
Set worksheet=excel.worksheets(1)
'Coloring Excell Sheet Rows
Set objrange=excel.activecell.entirerow
objrange.cells.interior.colorindex=37
'Coloring Excell Sheet Cell
worksheet.cells(2,1).interior.colorindex=36

23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.

'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set objrange=Nothing
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing

11) UFT 11.5 Features


UFT 11.5x is the combination HP Service Test and QTP

UFT is called as Unified Functional Testing where all HP testing related products
are combined into it

HP Service Test used to test the web services and hence UFT will also be used to
test web services

There are lot of changes in IDE when compared with QTP. All menu options
segregated based on their usage
o
All Script Run related options like Running, Debugging, Update,
Maintenance run modes etc there in Run menu
o
Record Related options like types of recordings, recording configurations
available in Record menu
o
Script design options like inserting Steps, Synchronization, checkpoints,
comments and transaction points available in Design menu
o
HP Quality Center is also combined to HP Application Life Cycle
Management. And so we call QC as ALM
o
All ALM connecting options available in ALM menu

There is an architecture change in Test design


o
Before we can open only one test at a time and create the actions in it
o
Now they have given a new feature called Solution where we can add
multiple tests to it
o
We can also edit multiple tests of the same solution at a time

o
o
o
o

There are some changes to the QTP View panes as well


Available Keywords is now ToolBox
DataTable is Data
Information and Missing Resources panes are combined in to Errors
Resources is now Solution Explorer

o
o
o
o

o
o

o
o

Test Flow is Canvas


ToDo became Tasks
Print log is output
Debug Viewer sub tabs are now divided in to individual panes
Watch as watch
Variables as Local Variables
Command as Console
A view for Break Points to show all break points of that solution
Call Stack: a new view to see the Function Call Flow
Changes in Recording
A new recording toolbar will opened when you start recording
This toolbar will help you
To create new actions
To insert synchronization and checkpoints
To switch between recording modes
To stop recording
A new recording mechanism introduced Insight Recording
This uses Image Based Identification for the objects

Changes in Object Identification


o
A new identification mechanism introduced Image Based
Identification
o
When you record using Insight recording It stores the images of the
objects in Object Repository
o
UFT finds the objects using the stored snapshots of the objects
o
This kind of identification useful when UFT fail to recognize the objects or
technology
o
Insight objects will not have any kind of properties
o
If required you can use Visual Relation Identifiers or Ordinal Identifiers
o
Smart Identification is not applicable for Insight Objects

o
o

Changes in Checkpoints
File Content Checkpoint introduced
Using this you can verify the data in HTML, PDF, MS WORD, RTF, TEXT

Files
o

You can also use Regular expressions to verify data in those files

Product Enhancements
o
Introduced code blocks in expert view
o
enhanced the intelligence for classes, functions, environment variables
and other keywords
o
Short cut key introduced CTRL+ALT+F5 to stop the test run
o
You can use XLSX files when importing data

Finally Dont forget to watch Product Movies about new features introduced
Repositories collection object
1.
'###############################################
2.
'
RepositoriesCollection Object
3.
'###############################################
4.
5.
' Purpose:Used to Add, Remove, Find and Change Position of Shared Object Repositories of
an Action in RunTime
6.
7.
'**************************
8.
'Adding Repositories
9.
'**************************
10.
'Syntax:- RepositoriesCollection.Add RepositoryPath [, Position]
11.
12.
RepositoriesCollection.Add "D:\ProjectSuite\AutomationSuite\OR\Main.t
sr",2
13.
14.
'**************************
15.
'Find Repositories
16.
'**************************
17.
'Syntax:- Pos = RepositoriesCollection.Find RepositoryPath
18.
19.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")
20.
21.
'**************************
22.
'Move Position of a Repository
23.
'**************************
24.
'Syntax:RepositoriesCollection.MoveToPos CurrentPosition, NewPosition
25.
26.
'Get Current Position
27.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")
28.
29.
'Move to Another Position
30.
RepositoriesCollection.MoveToPos RepositoryPosition, 1
31.
32.
'**************************
33.
'Remove Repository
34.
'**************************
35.
'Syntax:- RepositoriesCollection.Remove(Pos)
36.
37.
'Get Current Position
38.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")

39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.

'Remove Repository
RepositoriesCollection.Remove RepositoryPosition
'**************************
'Remove All Repositories
'**************************
RepositoriesCollection.RemoveAll()
'**************************
'Count Repositories
'**************************
print RepositoriesCollection.Count

14) Properties collection object how to use description in current decription


project
1.
'###############################################
2.
' Properties Collection Object
3.
'###############################################
4.
5.
'Introduction:6.
'This object is an extension of Description object. Using this we can do so
me with description object.
7.
' This is used to add, remove properties for a description object.We can als
o count how many properties used for a description.
8.
9.
' The unique feature of this object is we can add a property which is used
by other description object
10.
11.
'Ex:
12.
13.
'Create a Description for Link1
14.
Set LnkDesc1=Description.Create
15.
LnkDesc1("micclass").value="Link"
16.
LnkDesc1("name").value="Gmail"
17.
18.
'Create a Description for Link2
19.
Set LnkDesc2=Description.Create
20.
LnkDesc2("name").value="Gmail"
21.
22.
LnkDesc2.Add LnkDesc1(0)
23.
24.
'In the above example Iam creating the description for link objects
25.
'All link objects will have the same class value
26.
' To remove the redundancy I have used the same property value in other
link collection by specifying Property Index of a collection

27.
' The property Index Start from '0'
Here is the script to export Object Repository to Excel.
view plainprint?
1.
'############################################
2.
'Description : Exporting Object Repository to Excel
3.
'What Concepts used : Object Repository Model, Excel Object Model
4.
'Required Parameters: Object Repository, Excel Path (Creates Excel File)
5.
'Required Software : QTP/UFT Installed
6.
'Developed By : Sudhakar Kakunuri
7.
'############################################
8.
9.
'Declare Variables
10.
'************************************
11.
Dim srcRepository
12.
Dim ParentObject
13.
Dim excel, workbooks, rIndex, objRange
14.
Dim ObjectRepositoryPath,orExcelPath
15.
'************************************
16.
17.
'Specify file Paths
18.
'************************************
19.
'OR must be created before executing this
20.
'You can use .TSR, .XML and .BDB Object Repositories
21.
'An excel file will be created automatically with the name excel.xls
22.
ObjectRepositoryPath="C:\Users\sudhakar7\Desktop\PracticeScripts\O
R\createrequest.tsr"
23.
orExcelPath="D:\excel.xls"
24.
'************************************
25.
26.
'Load Object Repository
27.
'************************************
28.
'Creating Object Repository utility Object
29.
Set srcRepository = CreateObject("Mercury.ObjectRepositoryUtil")
30.
31.
'Load Object Repository
32.
srcRepository.Load ObjectRepositoryPath
33.
'************************************
34.
35.
'Create Excel file with columns, colors and Autofit
36.
'************************************
37.
'Create Excel Object
38.
Set excel=createobject("excel.application")
39.
40.
'Add New Workbook
41.
Set workbooks=excel.Workbooks.Add()
42.
43.
excel.Cells(1,1).value="ParentObjectLogicalName"

44.
excel.Cells(1,2).value="ParentObjectProperties"
45.
excel.Cells(1,3).value="ObjectLogicalName"
46.
excel.Cells(1,4).value="ObjectProperties"
47.
48.
Set objRange = Excel.Range("A1:D1")
49.
50.
objRange.Font.Bold = True
51.
objRange.Font.ColorIndex = 1
52.
objRange.Interior.ColorIndex=15
53.
54.
' rIndex variable used to enter values row by row
55.
rIndex=2
56.
'************************************
57.
58.
'fnExportORtoExcel will get objects and properties from OR
59.
'************************************
60.
'Calling a fnExportORtoExcel Function
61.
fnExportORtoExcel ParentObject
62.
'************************************
63.
64.
'Auto Fit all other columns & save excel
65.
'************************************
66.
'Autofit all columns
67.
excel.Worksheets("Sheet1").UsedRange.Columns.AutoFit
68.
69.
With excel.Worksheets("Sheet1").UsedRange.Borders
70.
.LineStyle = 1
71.
.Color = vbblack
72.
.Weight = 2
73.
End With
74.
75.
'Save Work Book
76.
workbooks.saveas orExcelPath,true
77.
78.
'Close Work Book
79.
workbooks.Close
80.
81.
'Quit from Excel Application
82.
excel.Quit
83.
'************************************
84.
85.
'Release Variables
86.
'************************************
87.
Set workbooks=Nothing
88.
Set excel=Nothing
89.
Set srcRepository=Nothing
90.
'************************************
91.
msgbox "Exporting Completed. Open "&orExcelPath&" to view the Excel O
bject Repository"

92.
93.
'************************************
94.
95.
Function fnExportORtoExcel(ParentObject)
96.
97.
'Get Objects by parent From loaded Repository
98.
'If parent not specified all objects in OR will be captured
99.
100. Set fTOCollection = srcRepository.GetChildren(ParentObject)
101.
102.
For RepObjIndex = 0 To fTOCollection.Count - 1
103.
104.
'Get object by index
105.
Set fTestObject = fTOCollection.Item(RepObjIndex)
106.
107.
Props=""
108.
109.
'Check whether the object is having child objects
110.
If srcRepository.GetChildren (fTestObject).count<>0 then
111.
112.
113.
'Get TO Properties List
114.
Set PropertiesColl=fTestObject.GetTOProperties
115.
116.
For pIndex=0 to PropertiesColl.count-1
117.
'Store properties in a variable with a comma delimiter
118.
Set ObjectProperty=PropertiesColl.Item(pIndex)
119.
Props=Props&","&ObjectProperty.name&":="&ObjectPro
perty.value
120.
121.
Next
122.
123.
If InStr(1,Props,",")=1 Then
124.
Props=Mid(Props,2)
125.
End If
126.
127.
128.
'Write Logical name and Properties in Excel Sheet
129.
excel.Cells(rIndex,1).value=srcRepository.GetLogicalName(fTestObject)
130.
131.
132.
133.
134.
135.
136.
137.
138.

excel.Cells(rIndex,2).value=Props
'Color the cells based class name
If InStr(LCase(Props),"micclass:=browser")<>0 Then
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
objRange.Font.Bold = True
objRange.Font.ColorIndex = 1
objRange.Interior.ColorIndex=36

139.
ElseIf InStr(LCase(Props),"micclass:=page")<>0 Then
140.
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
141.
objRange.Font.Bold = True
142.
objRange.Font.ColorIndex = 1
143.
objRange.Interior.ColorIndex=35
144.
145.
ElseIf InStr(LCase(Props),"micclass:=frame")<>0 Then
146.
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
147.
objRange.Font.Bold = True
148.
objRange.Font.ColorIndex = 1
149.
objRange.Interior.ColorIndex=40
150.
End If
151.
152.
'increase rIndex to enter data in next lines of excel
153.
rIndex=rIndex+1
154.
155.
'Calling Recursive Function
156.
fnExportORtoExcel fTestObject
157.
158.
else
159.
'This else block will execute when the object is not having any chil
ds
160.
161.
'Get TO Properties List
162.
Set PropertiesColl=fTestObject.GetTOProperties
163.
For pIndex=0 to PropertiesColl.count-1
164.
'Store properties in a variable with a comma delimiter
165.
Set ObjectProperty=PropertiesColl.item(pIndex)
166.
Props=Props&","&ObjectProperty.name&":="&ObjectPro
perty.value
167.
Next
168.
169.
If InStr(1,Props,",")=1 Then
170.
Props=Mid(Props,2)
171.
End If
172.
173.
'Write Logical name and Properties in Excel Sheet
174.
excel.Cells(rIndex,3).value=srcRepository.GetLogicalName(fTestObject)
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.

excel.Cells(rIndex,4).value=Props
'increase rIndex to enter data in next lines of excel
rIndex=rIndex+1
End if
Next
End Function
'************************************

Get Relative path from absolute path

If you use Relative Path for all the resources, the path displays
something like "..\..\QtpSudhakar\Libs\Sample.vbs". Sometimes we
may require to have full path to send it to results file or to know exact
location of the file for debugging. In this scenario to know the full path
of a resource which is associated with relative path, we have to use
below script. The script will automatically return the absolute path of a
resource which is specified with Relative Path.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

Dim QTP
Dim cLibs
Dim LibIndex
' Get Control over QTP
Set QTP=CreateObject("Quicktest.Application")
'Get All Associated Resources
set cLibs=QTP.Test.Settings.Resources.Libraries
For LibIndex=1 to cLibs.Count
' Using PathFinder object locate and display the Absolute path
msgbox PathFinder.Locate( cLibs.Item(LibIndex))
Next

16) WSH Script samples


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

'***************************************************
'How to popup a message with some wait
'***************************************************
Set WshShell = CreateObject( "WScript.Shell")
WshShell.Popup "message body", 5, "Title"
'***************************************************
'How to get the current UserName of logged in
'***************************************************
Set WshNetwork = CreateObject( "WScript.Network")
userName = WshNetwork.username
Set WshShell = CreateObject( "WScript.Shell")
WshShell.Popup userName , 50, " userName "
'***************************************************
'How to send keyboard inputs to application
'***************************************************
set WshShell = CreateObject( "WScript.Shell")
WshShell.SendKeys "QuickTest Professional"
'***************************************************
'How to get the value of the system environment variable
'***************************************************
Set WshShell = CreateObject( "WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM" )
WScript.Echo WshSysEnv("NUMBER_ OF_PROCESSORS" )
'***************************************************
'How to write and read registry
'***************************************************

31.
Set WshShell = CreateObject( "WScript.Shell")
32.
WshShell.RegWrite "HKCU\Software\ ACME\FortuneTell er\", 1, "REG_BINARY"
33.
WshShell.RegWrite "HKCU\Software\ ACME\FortuneTell er\MindReader" , "Goocher
!", "REG_SZ"
34.
bKey = WshShell.RegRead( "HKCU\Software\ ACME\FortuneTell er\")
35.
msgbox WshShell.RegRead( "HKCU\Software\ ACME\FortuneTell er\MindReader" )
36.
37.
'***************************************************
38.
'How to execute DOS commands
39.
'***************************************************
40.
Set oShell = CreateObject ("WSCript.shell" )
41.
oShell.run "cmd /K CD C:\ & Dir"
42.
'***************************************************

15) How to find data type of a variable


The data type of a variable can be indentified in two VBScript built-in functions.

1.

Vartype

2.

Typename

Vartype returns a numeric value indicating the sub datatype of a variable.


The below table contains return values that indicate respective subtypes.

Return Value

Sub

vbEmpty

vbNull

vbInteger

vbLong

vbSingle

vbDouble

Description

Datatype

Empty (uninitialized)
Null (no valid data)
Integer
Long integer
Single-precision floatingpointnumber
Double-precision floating-point
number

vbCurrency Currency

vbDate

Date

vbString

String

vbObject

Automation object

10

vbError

Error

11

vbBoolean Boolean

12

vbVariant

13

Variant (used only with arrays of


Variants)

vbDataObject A data-access object

17

vbByte

Byte

8192

vbArray

Array

Ex:

Dim x
x=10
msgbox vartype(x) 'Returns 2
In the above table 2 indicates vbInteger datatype.So x is an integer type.
Typename directly returns the name of the Sub Datatype of a variable.

Sub Datatype Description


Byte

Byte value

Integer

Integer value

Long

Long integer value

Single

Single-precision floating-point value

Double

Double-precision floating-point value

Currency

Currency value

Decimal

Decimal value

Date

Date or time value

String

Character string value

Boolean

Boolean value; True or False

Empty

Unitialized

Null

No valid data

<object type> Actual type name of an object


Object

Generic object

Unknown

Unknown object type

Nothing
Error

Object variable that doesn't yet refer to an


object instance
Error

Ex:

Dim x
x=10
msgbox typename(x) 'Returns Integer
There are some more VBScript Built-in functions to find whether a
variable datatype is specific datatype or not.
IsArray Returns a Boolean value indicating whether a variable is an
array or not.
IsDate Returns a Boolean value indicating whether an expression can
be converted to a date.
IsEmpty Returns a Boolean value indicating whether a variable has
been initialized.
IsNull - Returns a Boolean value that indicates whether an expression
contains no valid data (Null).
IsNumeric - Returns a Boolean value indicating whether an expression
can be evaluated as a number.
IsObject - Returns a Boolean value indicating whether an expression
references a valid Automation object.
Built in functions are available for only these datatypes. You can write
built function for every datatype like below
'*******************************
Function IsString(oValue)

If vartype(oValue)=8 then
IsString=true
Else
IsString=False
End If
End Function
'*******************************

Vous aimerez peut-être aussi