0% found this document useful (0 votes)
796 views151 pages

QTP World

Entry criteria are used to determine when a test plan is ready to execute, including setting up the test environment, successfully installing required software, and ensuring all prerequisites are met. Exit criteria are used to determine when to stop testing, such as covering all major functionality as specified in the test plan, completely executing all test cases, having software that is 80% bug-free with no high priority or severity bugs remaining, and reviewing and finalizing all documents. Descriptive programming involves writing test scripts without using the object repository by directly specifying object properties and values using the object spy. It is useful when objects are dynamically changing, when QuickTest is unable to recognize objects, or when the object repository size is large.

Uploaded by

raghu3042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
796 views151 pages

QTP World

Entry criteria are used to determine when a test plan is ready to execute, including setting up the test environment, successfully installing required software, and ensuring all prerequisites are met. Exit criteria are used to determine when to stop testing, such as covering all major functionality as specified in the test plan, completely executing all test cases, having software that is 80% bug-free with no high priority or severity bugs remaining, and reviewing and finalizing all documents. Descriptive programming involves writing test scripts without using the object repository by directly specifying object properties and values using the object spy. It is useful when objects are dynamically changing, when QuickTest is unable to recognize objects, or when the object repository size is large.

Uploaded by

raghu3042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 151

1.

What is exit criteria and entry criteria in test automation


Entry Criteria: Use to determine that test plan is ready to execute
1. Setup test environment that is required for particular test plan
2. S/W or application has been installed successfully.
3. All required / specified per-requisite are there.
Exit Criteria: Use to determine that it is the time to stop testing like...
1. All major functionalists have been cover as specify in test plan
2. All test cases are completely executed or not
3. S/W or application is bug free (up to 80%) and no higher priority
or higher severity bug in application.
4. All the documents should be reviewed, finalized or signed off.

2. I have a 10 lines of qtp script, while executing i got an


error at line 7 but i dont want to stop the execution i want
to continue the execution up to last line and display the
test result window, wts the syntax we use?
There are 3 ways to handle unhandled exception
1)File -settings run-run settings tab
2)recovery scenarios which can be done with ettings or programtically using recovery object
Resources
recovery scenario manager
scenario
add recovery scenario from function library or else add function defination to library
for trigger events 1)object state error
2)pop up window
3)application creash
4)tset run error
3) Vb script error handlers like on error resume next

3. Apart from VB script What are the fundamental criteria to

gain the knowledge to write QTP script without OR and


recording ?

In order to develop this script we should know the test


object descriptive properties & values (By using objectspy)
Ex:Static Descriptive program for login page(Banking
application)

Browser("name:=usRanfordbank").Page("title:=Ranfordbank").WebEdit("html
id:=txtuid").Set "Admin"
Browser("name:=usRanfordbank").Page("title:=Ranfordbank").WebEdit("html
id:=txtpwd").Set "suresh"
Browser("name:=usRanfordbank").Page("title:=Ranfordbank").Image("html
id:=login").Click
------------------------------------------------------------Ex:
Dynamic Descriptive program for login page (banking application
set br=description.create
br("name").value="usRanfordbank"
set pg=description.create
pg("title").value="usRanfordbank"
set uid=description.create
uid("html id").value="txtuid"
set pwd=description.create
pwd("html id").value="txtpwd"
set img=description.create
img("html id").value="login"
Browser(br).Page(pg).WebEdit(uid).Set "Admin"

Browser(br).Page(pg).WebEdit(pwd).Set "suresh"
Browser(br).Page(pg).Image(img).Click

How can i parameterize the standard checkpoint using Excel


sheet where my expected values are there??
suppose i want to test a application with diffent value and
want to run 5 iteration?? for each iteration, values will
be exported from excel sheet as input. Now i will store
some expected values in the excel sheet, which i want to
check in the application whether expected equals to actual
value???

First Insert the Standard Checkpoint for the desired statement using Insert --> Standard checkpoint,u
have to keep the QTP tool in recording mode for this.
After the checkpoint has been inserted then a script will be generated in the QTP, now
1. Right click on the checkpoint statement
2. Select the option checkpoint properties
3. Select the option parameter
4. Click on the parameter option button
5. Select the desired column name
6. Click on OK
7. Click on Ok

why a framework is needed in qtp


automation frame work is nothing but a set of guidelines
designed by expert to accomplish a task in an
effective,eficcient and an optimised way.
there are 4 different types of frame work 1)linear 2)

modular 3)keyword 4)hybrid


max we follow keyword framework
keyword frame work is nothing but creating a software
structure like
1)scripts 2)object repository 3)test data 4)recovery
scenario 5)log files 6)library files etc
1)create scripts and save it in scripts component
2)create shared o.r and save it in o.r component
3)create test data and save it in test data component
etc
after creating all these components include the files or
components to script or qtp and execte the script

how to merge object repositories in qtp for n different


applications
using objet repository merge tool at object repository
manager, we can merge existing shared repository files
information into new file
NAVIGATION:Object repository manager--->Tools
menu---->select the object repository merge tool---->Browse
shared repository
files----->click ok---->save it as .tsr(extension)

What is the condition or scenario that leads the use of object


spy in qtp? (while recording we can get all the properties)
then wat leads to use this?

Object spy is of great use when writing Descriptive


programming. It heklps you to find the exact properties
with which you would like to identify an object.

Moreover it is also of use to sometimes find out the exact


changes in the properties of an object when a script fails.
Hoipe this helps.

what is the purpose of SetTOProperty Method?


You want to modify a property value of an temporary test
object during that run session, you use setTOProperty.
for ex: in your OR, there is an obj(tempObj) with property
name "Hello". If you want to change this property to "Hello
uday", use setTOProperty.
Object.setTOProperty "name","Hello uday"
Note: The updated value is not changed in OR.

difference between GetRoProperry and GetToProperty.and


where we've to use exactly those properties
GetROProperty and GetTOProperty both comes under methods in
QTP.
1) GetROProperty: We can you this method to capture runtime
property value into variable.
OR
We can use this method to capture the object property value
from the application
Code:
For window Application:
Variable = Window("Window Name").Dialog("Dialog
Name").Object("Object Name").GetROProperty("Property Name")
For Web Application:
Variable = Browser("Browser Name").Page("Page Name").Frame
("Frame Name").Object("Object Name").GetROProperty
("Property Name")
Example: To know the whether the push button is enabled or

not during runtime.


Variable = Window("Flight").Dialog("Login").Winbutton
("Start").GetROProperty("Enabled")
Here if the button is Enabled during runtime the Variable
is asgined with "True" else "False".
2) GetTOProperty: We can you this method to capture Test
Object property value into variable.
OR
We can use this method to capture the object property value
from the Object Repository.
Code:
For window Application:
Variable = Window("Window Name").Dialog("Dialog
Name").Object("Object Name").GetTOProperty("Property Name")
For Web Application:
Variable = Browser("Browser Name").Page("Page Name").Frame
("Frame Name").Object("Object Name").GetTOProperty
("Property Name")
Example: To know the value of Push button Enabled propety
from the Object Repository.
Variable = Window("Flight").Dialog("Login").Winbutton
("Start").GetTOProperty("Enabled")
Here it will give the value of the property that is stored
in the object repository.

WHAT IS THE DESCRIPTIVE programming when it is useful? &


when to use this ?
without using the objectrepository, and by using the
objectspy we will write the DESCRIPTIVE programming .

when ever we will go to DESCRIPTIVE programming :1.when ever objects are dynamicaly changing.
2.when ever QTP is not going to recognise the objects.
3.when ever objectrepository size is huge automatically QTP
wil get down slow.
4.when ever not yet develop the build then only we will use
DESCRIPTIVE programming .
List few scenarios where Descriptive Programming MUST be
used?
1. For an object which will be used only once or
twice, theres no need to use the slow, complex Object
Repository. DP should be used.
2. In case the identification properties and values of
an object match more than one object; QTP will throw
an "Objects description matches more than one of the
objects currently displayed in your application" error (If
OR is used).
DP easily deals with double objects by using the
index property. We can add Index:=X to the description
strings (when X is a zero-based counter), and QTP will
point to object #X.
3. Some objects change hierarchies i.e. an object will
appear under a different parent each time (e.g. a pop-up
which appears under the initiating sub-window). In some
applications, the only way to work with such objects is
with DP.
4. When using an Object Reference in an External
Function, it is difficult to make sure that the relevant
object is being defined in the Calling Actions Object
Repository or Even if it is defined, does it have the same
Logical Name? Descriptive Programming is the only option
left.

5. Instead of working with a single object at a time,


we can gather all the objects which answer to our
identification properties, and work with them as a
collection.
For Example:- Suppose you are testing Yahoo Website.
After you login, it lists all the mails present in your
inbox with a checkbox for each mail. Using this checkbox
you can select a mail for deletion or for moving it etc.
But when you design your test, you do not know how
many check boxes (mails) will be displayed on the page, and
you cannot, of course, know the exact object description of
each check box. In this situation, you can use a
programmatic description to instruct QuickTest to perform a
Set "ON" method for all objects that fit the description:
HTML TAG = input, TYPE = check box.
6. When testing a NOT YET DEVELOPED build, DP must
be used.
7. Size of Object Repository adversely affects the
performance of QTP. Huge OR slows QTP down.

write a VBscript code to parametrize test script using test


data from sqlserver database?

first connect to database using the following script

set sqlconnection=createobject("ADODB.connection")
set sqlrecordset=createobject("ADODB.recordset")

To open the connection


sqlconnection.open "You have to mention your database
connection string"
sqlrecordset.open "Give your query",sqlconnection
to run through all the records
if not sqlrecordset.EOF then

suppose your are going to set it to a textbox then


Browser(browsername).page(pagetitle).webedit
(testboxname).set sqlrecordset(columnname)

end if

OR
dim con,rec
set con=create object("adodb.connection")
set rec=create object("adodb.recordset")
con.open"provider=sqloledb.1;server=name;username=scott;pwd=tiger;database=dbname'
rec.open"sql statement"con
while not rec.eof
window("winmame").winedit("uname").set rs.fields(un)
in the same way use the data
loop

How to count no of edit boxes on the page?

Set oDesc = Description.Create()


oDesc("micclass").Value = "Webedit"
Set Lists=Browser("Login").Page("Application").ChildObjects
(oDesc)
NumberOfLists = Lists.Count()
msgbox NumberOfLists

Please use below DP to Counts(Links,web Button and WebEdit Box)of any web
applications.simply you need to copy from here and past in QTP.
SystemUtil.Run "iexplore.exe","https://accounts.google.com/ServiceLogin?
hl=en&continue=https://www.google.co.in/%3Fgws_rd%3Dcr%26ei
%3De_HIUsCCNcqOrgfT0oCAAQ"
wait 10
Set Desc = Description.Create
Desc("micclass").Value = "WebEdit"
Set Edits = Browser("creationTime:=0").Page("micclass:=Page").ChildObjects(Desc)
MsgBox "Number of Edits: " & Edits.Count
Set LinkObj=Description.Create
LinkObj("micclass").Value = "Link"
Set Links = Browser("creationTime:=0").Page("micclass:=Page").ChildObjects(Link)
MsgBox "Number of Links: " & Links.Count
Set btns=Description.Create
btns("micclass").value="WebButton"
Set dlg=Description.Create
dlg("name").value="signIn"
Set ocollection = Browser("creationTime:=0").Page("micclass:=Page").ChildObjects(btns)
msgbox ocollection.count
Set ImageObj=Description.Create
ImageObj("micclass").value="Image"
Set dlg=Description.Create
dlg("name").value="Image"

Set oImage = Browser("creationTime:=0").Page("micclass:=Page").ChildObjects(Image)


msgbox oImage.count

How to get 3 letters from a string?

Using Trim(str,3)
Using mid(str,1,3)

How to remove the spaces in a string Ex: "Welcome to


QTPWorld" ?
1.
Str = Welcome to QTP World
Replace(Str," ","")
2.
Dim str
str="welcome to qtp"
arr=split(str," ")
For i=0 to Ubound(arr)
abc=abc&arr(i)
Next
print abc

3.

str = "Welcome to QTP World"


arrsplit = Split(str," ")
arrjoin = Join(arrsplit,"")
MsgBox arrjoin

If already everything is tested using White-Box testing,


then what is the need of using Black box testing?

White-Box testing is used to test the internal logic of the


code, where as black box testing is used to test in all
possible ways by specifying the range and etc.

White box is to do with code testing and is mainly done by


the developer, it is also known as Unit testing.
Black box is more advance testing, it includes funtional,
regression, system testing etc. This is mainly done from
end user prospective (Customers). If customers are able use
with no errors, then the product is of high quality.

Write a script to only download pdf's if there are 20 links on a page.

Set oLink = Description.Create


oLink("micclass").value = "Link"
Set oPage = Browser("title:=.*").Page("title:=.*").ChildObjects(oLink)
PdfCount = 0
For i = 1 To oPage.Count-1

oPdfFiles = oPage(i).getROProperty("url")
print oPdfFiles
If Right(oPdfFiles,4)=".pdf" Then
MsgBox oPdfFiles
count = count +1
End If
Next
MsgBox PdfCount

dim objIE
Set objIE = CreateObject("InternetExplorer.Application")
objIE.visible=true
objIE.Navigate "your url"
Set ObjDoc = objIE.Document
objhref=objdoc.documentElement.getElementsbyTagName
("a").item(0).href
if (Instr(objhref,".pdf")>0) then
objdoc.documentElement.getElementsbyTagName("a").item
(0).click
End if
This will download the pdf doc into the current opened
browser.

write the regular expression for date format of mm/dd/yy?

Here is the format for the input.


MM will be 1 to 12 "[1-9]|1[0-2]"
DD will be 1 to 31 "[1-9]|[1-2][0-9]|3[0-1]"
YY will be "[0-9][0-9]"

Hence MM/DD/YYYY will be


"[1-9]|1[0-2]/[1-9]|[1-2][0-9]|3[0-1]/[0-9][0-9]"

plz tel me what is the differnce between QC & QTP?


QC: It is a Test Management Tool, which is used for Managing
the Entaire Testing Process from Begining of the Project to
end. In Deeply by using the QC we can Store, Add, Delete
the REQUIREMENTS in Requirements Tab, We will Store Test
Plan, Test Sceniories, Test Case Documents in the Test Plan
Tab, we will Execute Test Cases and Results in the Test Lab
Tab(Internally there is a connection between Test Plan and
Test Lab), and the final and Excelent feature which the QC
will have Defects Tracking and Reporting, in briefly if at
all we will get any defects in executing the application
then we should raise the Defects through the DEFECTs Tab.
i.e enter in to the Defects Tab and click on the New Defet
Button. And also there are two more tabs are available in
QC but those two are used in Manager Cadder people not by
the Testers. QC is Used in Both MANUAL as well as QTP but
the thing is for QTP we will store and Execute Test Scripts
insted of Test Cases in the
Test Lab.
QTP: Well Comming to the QTP, it is a Functional Test Tool.
Unlike Manual Testing here we use a Tool called QTP
qtp is the automation tool there we write the scripts and
execute the scripts
qtp is the process to build the application only on u r pc but qc like total process stored in qc and also
u upload the new version that means abdate version as well as old version also available any one
can take any data for the deployed build that is u need the coding if u get the coding on the qc at
time tester,designer,end user can take the used data

Diff. between keyword driven Data driven testing?


Data-driven testing is a methodology used in Test automation
where test scripts are executed and verified based on the
data values stored in one or more central data sources or
databases. These databases can range from datapools, ODBC
sources, csv files, Excel files, DAO objects, ADO objects, etc.
Keyword-driven testing or Table-driven testing is a Software
testing methodology as part of the Test automation
discipline that separates the programming work from the
actual Test script so that the test scripts can be developed
without knowledge of programming. As a result the test
scripts can be maintained with only minor updates, even when
the application or testing requires significant changes.

Keyword Driven Testing: In this testing tester interaction


is there at time of testing. we can give the values with
help of
Syntax:- Variable = inputbox("String")
Ex:- a = inputbox("Enter the value for A ")
In the above example a is the variable it's stores
the value at the runtime. and u can use this variable as a
parameter of any object at runtime.
Data Driven Testing: In this testing there is no
interaction of tester. here we can use datasheets or
frontend grids as parameters to the application.
We can get values from data sheets

Syntax:- variable = datatable("column name","sheet


name")
Ex:- empno = datatable
("employee_no","dtGlobalSheet")
In above example
Empno is variable
Employee_no is column name
dtGlobalSheet is Sheet name
we can use these variable in our application as a
parameter.

what is life cycle of automation testing ?

-> Test Planning


->Analycis Appl Under Test
->Setup Test Environment
->Generate Basic Tests
->Enhancing Tests
->Debug The Test
->Run Tests
->Analyze Results
->Report Defects

1.Analysis the requirement


2.test plan
3.analysis the application
4.preparation of test case
5.preparation of test data
6.object configuration
7.using object repository or descriptive programing
8.scripting
9.execution
10.Result

write script to read and write data from file ?

First u create obj for file


set fso=createobject("scripting.filesystemobject")
set <var>=fso.opentextfile("FileName",[IOMode],[create])
IOModes 1-Readonly Create-True
2-Write False
8-append
Readline,writeline...use to access the data.

there are having 10 checkboxes..how can i check only first


5 check boxes by using descriptive programing.

set objCheckBox=Description.Create()
objCheckBox("micclass").Value="WebCheckBox"
set objChildObjects=Browser("micclass:=Browser").Page
("micclass:=Page").Childobjects(odesc)

for i=1 to objChildObjects.Count


If i=5 Then
Exit For
End If
objChildObjects(i).Set "ON"
Next
OR
Dim objCheckbox
set objCheckBox=Description.Create()
objCheckBox("micclass").Value="WebCheckBox"
set objChildObjects=Browser("micclass:=Browser").Page
("micclass:=Page").Childobjects(odesc)

for i=1 to 5
objChildObjects(i).Checked
Next

What are the three challenges U faced during automation


testing of your application.

1. Designing an architecture for automation


2. deciding technology/tool with which everyone at least aware
3. explaining the architecture to subordinates so that while
automating they will create as per that

1.Till what level automation should be done?


2.Do you have sufficient and skilled resources for automation?
3.Is time permissible for automating the test cases?

How we can differentiate between stand alone application and


web application in QTP?
stand alone environmnet:
It is a single tier application. here presentation
layer,bussiness layer and database layer will be present
client server.
web based application:- It is three tier application.
Presentation layer will be present in client server ,
business layer will be present in application server and
database layer will be present is database server.Mainly it
is used whenever the application can accessed all over the
world with minimum no.of users.On that time we case use the
web based application.

stand-alone-application:
Software installed in one computer and used only one person.
Ex: calculator,Adobe Photoshop,MS office etc.
Web application:
Any Application Software accessed through browser is called web application.
Ex:yahoo.com,gmail.com
Client/Server Application:
Here we are installing both client and server software to access the application
Ex:yahoo messenger,Gtalk,ATM

write script for finding number of broken links in web page?

Using Automatic Page checkpoint:


Go to Tools > Options > Web > Advanced and check the two
boxes labeled Create a checkpoint for each page while
recording and Broken Links.
Now every time you record a new page, QTP will automatically
include a checkpoint for broken links.
OR
By manually creating a Page checkpoint:
QTP does not provide a direct menu option to incorporate a
page checkpoint. You need to take the help of standard
checkpoint. Start recording session > Insert > Checkpoint >
Standard Checkpoint (OR press F12). Place and click the hand
pointer anywhere on your web page from "Object selectionCheckPoints Properties" window click OK it takes you to
"Page checkpoints Properties" where in click on 'Broken
Links" option.
Run the above script. Go To Test Results > Your Check Point.
Check the status of all links under Broken Links Result
If you want to verify links pointing only to the current
host check the box titled Broken Links- check only links to
current host under Tools > Options > Web. Similarly If you
want to verify links pointing to other hosts as well,
uncheck it.

To find no:of links present in any open web page:************************************************


dim br,pg,objbr,objpg,linkcoll,lcount
br=Browser("micclass:=Browser").GetRoProperty("name")

pg=Browser("micclass:=Browser").Page("micclass:=Page").
GetRoProperty("title")
set objbr=description.create
set objpg=description.create
set odesc=description.create
odesc("micclass").value="Link"
objbr("name").value=br
objpg("title").value=pg
set linkcoll=Browser(objbr).Page(objpg).ChildObjects(odesc)
lcount=linkcoll.count
msgbox lcount

How can we check whether a particular sheet loaded (existed)


or not in Data Table.

On Error Eesume Next


datatable.getsheet("Sheet name")
'Checking error number, if no error then returns 0
If err.count<>0 Then
msgbox "Sheet not available"
Else
msgbox "Sheet available"
End if
On error go to 0

We can use datatable.getsheet("sheetname")


to access any sheet at run time

U can debug and watch the data table at run time, so that
we can see that particular sheet is loaded or not.. or u
can use wait statement to view i

Is there any function or vbscript in QTP to clear the


cookies,sessions. Please help me in this.

webutil.DeleteCookies

You can write your own function also:


Public Sub MyDelCookies()
'Option Explicit
Dim strPath, WshNetwork, fso, objFol, objFile, var
strPath="c:\Documents and Settings\"
Set WshNetwork = CreateObject("WScript.network")
strPath=strPath + WshNetwork.UserName +"\Cookies"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder(strPath)
Set objFile = objFol.files
For Each var in objFile
If var.name<>"index.dat" Then
var.delete
End If
Next
Set WshNetwork=Nothing
Set fso=Nothing
End Sub

Suppose u run ur script today and it is working fine ,nobody


has changed the setting and all.u r the owner for the

script. But when tomorrow I ran the same script again it got
failed and It didn't able to identify one object. Can you
tell me what would be the reason for this

1.you didn't click or enables the add-ins while open the qtp
2.or you first open application after that you open the qtp
Properties of the object might be changed
New build got deployed in which the object properties used
for identity might have changed
Thr resourse file might bw missing from where u are
runnuning the scripts, since you are running it from the
different machine you would not have added those resource
files , shared repository etc

where u maintain qtp scripts in ur company

Scripts will be maintained as per the framework followed depends on companies.because framework
varies from org to another org.
Scripts stored under Test Scripts Folder in C:\Framework\Testscrpts..
We maintain(Version Controlling)our scripts in tortoise SVN.
In QC OR ALM we are maintain QTP scripts

what is smart identification in qtp? pls any give details?


Smart Identification : Its a mechanism provided by Quick
Test to identify dynamic bjects whose properties are
changing time to time....( Say a Submit button changes to
Save after clicking once)
Now the test property of that button is changed.If we

generate the script statement


Window("windowname").dialog("dialogname").winbutton
("submit").click
beacuse submit button is no more available in window
Generally Object Identification is done using the physical
description (Mandatory and Assistive properties) of that
object in the object repository.
But If we want to enable Smart Identification we have 2
ways.
1) enable Smart Identification for Object class
2) enable Smart Identification for a single Object
If we want to enable Smart Identification for entire object
class
Go to Object Identification---> select the environment--->
select the object class---> check the enable smart
identification checkbox in object Identification dialog
If we want to enable Smart Identification for a specific
object
Go to Object Repository---> select the environment--->
select the object class--->select the object---> check the
enable smart identification checkbox in object Repository
dialog
And we should select the Base Filter and Optional filter
properties for the selected object class/object.
When we enable this smart Identification Quick Test will
try to locate the object based on these properties only.

what is On Error Resume Next ?

This is one of the ways of error handling in QTP. When an


unpredictable error occurs in running the script, instead
of stpoing the execution the script moves on to the next
step and continues execution.

what are the different kinds of frameworks in automation?


frame work is a set of guide lines, assumptions and process
developed by experts in order to perform a tasks in an
affective,efficient, and optimized way
automation frame work is not a qtp feature its a third
party concept and this is purely local concept "frame work
may vary from company to another types of frame works
--- record/playback or linearframe work (it is first
generation frame work)
--- modular frame work
---data driven frame work
---hybrid frame work
---key word driven frame work
in the above frame works key word driven frame work is
famous in the industry

is it possible to change the date format like MM/DD/YY


into DD/MM?YY through script in QTP
Strday = day(date)
Strmonth = month(date)
Stryear = right(year(date),2)
Newformat = Strday&"/"&Strmonth&"?"&Stryear
msgbox Newformat

Write a function which returns the addition of two numbers.


give the value of the numbers outside the function.

1) Write the below code in notepad and save it as .vbs file.


Function Code:
Public Function Addition_Of_Two_Numbers (Value1,Value2)
Result = Value1 + value2
Addition_Of_Two_Numbers = Result
End Function
2) Open Quick Test Professional Functional Testing Tool
3) Go to File-> Settings-> Resources-> Click '+' symbol
under Associated Function Libraries: and upload the abouve
saved file.
4) Go to Expert View.
5) Write this VBScript Code:
Sum_Of_Two_Numbers = Addition_OF_Two_Number(3,4)
Msgbox "The Addition Of Two Numbers
= "&Sum_Of_Two_Numbers
6) Save this Action and run(F5) it.
This will display the answer 7 in a messagebox.
Note: You can change the constants 3,4 as you required.
Example: if we want to know the sum of 13 and 1 we
will get the answer as 14.

how to display message with out using msgbox function?

print is different from message box. We can


display message box by this way also.
Set oShell = CreateObject("WScript.Shell")
Mesgbox = oShell.Popup("Do you Want to
Continue",10,"Welcome",3)

Re Engineering the regression testing from 0% to 60%


automation.
This has saved 4-mandays in every release.
what doeas this statement means

Re-Engineering means making changes to the existing one.


It may be a process or a flow and it depends upon the
platform and the situation too.
Regression Testing is the one which we will perform for
each and every release. Hence automation this manual task
can be helpful in reducing the time taken for execution of
the regression manual scripts.
As we can not automate all the areas it is said that upto
60% will work out.
In gist we can say Automating the Regression script upto
60% have saved 4 Mondays of our execution time in each
release.

can i able to connect any version of qtp to any version qc

No, We can't connect any version of qtp to any version qc.If


scripts are developed in Qtp 8.0 version & Qc 8.0 version.It
is OK But,If u developed in Qtp 8.0 & Qc 8.0 & Run The
scripts in 9.0 Version using Qc 8.0 is not
possible.So,Better to use same version.

YES, Through Add-ins

what is the criteria for choosing test cases for automation?


Ex: if you have some 300 test cases, then how many you choose for
automation. what is criteria of selecting?

they r no of criteria where we choose automating a


particlar feature ttesting like
1)when the test cases have to repeated for every build we
have to choose autoamting them
2)if the test cases are having data values to be passed in
that cases it is goodidea to automate them for better
coverage
3)and when the test cases are tested for compatibility fo
the system then this is the other situvation where we can
automate

A webPage has a ComboBox with 10 values in it.


Write a script to select 4 vales from it using CTRL key

set listObj=Browser("micclass:=Browser").Page
("micclass:=Page").WebList("micclass:=WebList","name:=XXXX"
listObj.select "#1"
listObj.ExtendSelect "#2"
listObj.ExtendSelect "#3"
listObj.ExtendSelect "#4

A web Page has 2 frames. Find out the number of weblist


items in the second frame of the page.

set FrameObj=Browser("micclass:=Browser").Page
("micclass:=Page").Frame("micclass:=Frame","index:=2)
Set wList=description.create
wList("micclass").value="WebList"
set wListObj=FrameObj.ChildObjects(wList)
wListcount=wListObj.count
msgbox wListcount

56.A web Page has a webtable with four columns and four rows.
The first column is of ID and has values of 100,100A,A100,100y
Find out the number of rows whose ID starts with 100.
Similarly the last column is 'number of links'. Each row in
the last column has values like link1,link2,link3 etc
Find out the number of links where id is 100

set objWT = Browser("micclass:=Browser").Page


("micclass:=Page").Webtable("html id:=xxxx")
rowCount = objWT.Rowcount
Dim Pass
For i = 2 to objWT 'As row#1 is always a column
num = objWT.GetCellData(i,1)
numCheck = mid(num,1,3)
If strComp(numCheck, "100", 1) = 0 Then
Pass = Pass + 1
End If
Next
msgbox "Number of expected Rows:" &Pass

A dialog is diplays " Transaction 254689 has been


successfully completed" How to get the transaction ID from
the message ?

Str="Transaction 254689 has been successfully completed"


Arr=Split(Str," ")
for i=0 to ubound(Arr)
if IsNumeric(Arr(i))=true then
Msgbox "Transaction ID is "& Arr(i)
End if
Next

A web page title might be [email protected] or [email protected] or


[email protected] what mandatory properties can be the page
identified.Give the regular expression for that

Browser(miclass).page(title:=^[a-z]+@[a-z]+\.[a-z]{2-3}).
In "title" propert of page put-------> .*@.*l\..*
.*x.* is the regular expression for that web page

A web page has two butons with same properties and rotating
in clockwise direction. how to click on any of the button?

As the buttons are having same properties and their


locations are being changed continuously.. you can go with
the index Or Creation time properties of the Ordinal
Identifier to identify the particular button.

'Use the following code to click on the second button


Browser("").page("").webbutton("name:=XXX","index:=1").click
similarly to click on 1st button change index value to 0
You can also use highlight to conform particular webbutton on the webpage which you wanna click
Browser("").page("").webbutton("name:=XXX","index:=1").highlight

how qtp will recognise if application is run on many browsers


by using Browser("CreationTime:=0").page(micclass:=page).......
here QTP recognises Browser("CreationTime:=0") as first

opened browser and Browser("CreationTime:=1) as second and


so on...

In A Table there are some columns and dynamic rows and in each
row in first column there is a link with name. upon clicking on
that link it will show some details. write the vbscript to check
that link without descriptive programming?

Follow the below given steps:


1. prepare an excel sheet whose colums are dynamic and rows
are static.
2.Rename the "sheet1" with any name say for an eg:- "Data"
3.suppose excel sheet contains columns like Name, class and
section. and in "Name" column you have to search for the
word "Testing".
4.In Qtp write the following scipt.
datatable.addsheet"vital"
'Vital is the name of the virtual sheet in QTP'
datatable.importsheet"Pathe of the Excel sheet","Data","vital"
rc=datatable.getsheet("vital".getrowcount
MsgBox rc
For i=1 to rc
Dim a
a=datatable.value="Name","vital"
if a="Testing"
MsgBox "Testing"
Endif
Next

I think, the table mentioned here is not Excel sheet. It is


a html table on a web page, where 1st colum contains links
with name="name".
So, the porblem is when you 1st record the script, there
are 2 rows (example) and 2 links with description = "name",
so, qtp object repository will add location property to
link (1st link = Location:0, 2nd Link = Location:1 etc..)
When you execute the script, there are 5 links with
name="name" (because of 5 dynamic rows added). Now, how do
you select /click other 3 links (3,4 and 5). Because, you
have only 2 Links recorded.
The 1st and best solution is descriptive programming. The
interviewer asked for without desriptiev programming.
The psedu code is given below.
-- Record only one link (with location:0)
Do
browser.page.frame.Link(location:0).Click
-- Change object description for Link, Update Location
to 1 instead of 0.
bExist = Browser(b).Page(p).Link.Exists
Loop While bExist = True

We have 10 rows of records in data table, but we have to run


4th, 5th and 6th rows only. How can we handle this scenario
in QTP?

Go to File => Settings. In 'Run' tab, choose the option,


Run from Row. Set '4 to 6' there

Datatable.setcurrentrow(4)
then use fpr loop, 4 to 6

DataTable.ImportSheet "C:\Users\Anil\Desktop\Testing_QTP.xls
",1,"Global"
numRow=DataTable.GlobalSheet.GetRowCount
msgbox numRow
For i=4 to 6
DataTable.SetCurrentRow(i)
disp=DataTable.Value ("Test",1)
msgbox disp
Next

Let me add some more to second answer:


In QTP Data Table Methods we have three methods to work on
rows:
1) SetCurretRow
2) SetNextRow
3) SetPrevRow
Here in our case the best method is SetCurrentRow.
1) SetCurrentRow: We can use this method to take a
specified row s current row in run time datatable. By
default QTP points to 1st Sheet 1st Row.
Syntax: SetCurrentRow(Row Number)

Code:
Datatable.SetCurrentRow(4)
For Current_Row = 4 to 6 step
/* To write the data into the datatable
Datatable.value(Current_Row, Column) = "Sandeep"
OR
/* To get data from the datatable.
Cell_Value = Datatable.value(Current_Row, Column)
Next
Note: Here the variable column is respective column number
on which we want to act.

Given scenario is like this: One Web table is there


and you have to search and retrieve a cell data which is
equal to the given number say:123. Assume you have given
with the column name/id of the table where the number may
exist. So now you have to go to the given column and search
for the number 123 and retrieve it along with the row
number of it.

Vinay there is no need to go this much.we can directly


retrieve using getcelldata metho
row=Browser(..).Page(..).Webtable(..).Rowcount
column=Browser(..).Page(..).Webtable(..).columncount
For i=1 to row
for j=1 to column
val=Browser(..).Page(..).Webtable(..).getcelldata(i,j)

if val="123" then
msgbox "the row is "&i

row=Browser( ).Page( ).WebTable( ).GetRowWithCellText("123")


it will returns the Row Number in which the cell data is 123

Hello,
For this scenario we can write in Descriptive program,
You need to create an object and get the total rows count in
the table. Check the below script.
Let say the "id numbers" in the "ID" column are links.
Dim i,j,k
Dim Numberofrows, Links, IDLink, Val
Set IDLink=description.Create()
IDLink("micclass").Value="Link"
IDLink("html tag").Value="INPUT"
IDLink("abs_x").Value=abs_xvalue "note: you can get the
abs_x value of the column and enter the value here"
Set
Links=Browser("micclass:=Browser").page("micclass:=Page").ChildObjects(IDLink)
Numberofrows = Links.Count()
Do While i<=Numberofrows-1
val=trim(Browser("micclass:=Browser").page("micclass:=Page").Link("html
tag:=INPUT","abs_x:="&abs_xvalue,"html
id:=TD","index:="&i).GetRoProperty("value")
if Val = "123" then
msgbox "the Value 123 is in the row:" &i+1
Exit Do
End if

i=i+1
Loop

How can i count "spaces" in any sentence or a string


if suppose " It is a Testing question"
Here we have 4 gaps(spaces)
Is there any function to find out spaces between words
s="Gita is a good girl "
d=split(s," ")
count =0
For i=ubound(d) to 1 step -1
count =count +1
Next
msgbox count
a=inputbox("enter the string")
countspaces=len(a)-len(replace(a," ",""))
msgbox "count is" & countspaces

vbscript to sort array in ascending and descending order ?

how to calculate no. of repeating characters in a a


string..please give me the code
mystring = "mississipi"
slen=Len(mystring)
msgbox slen
ws=Len(replace(Mystring,"s",""))
msgbox ws
charcount=Len(mystring)-Len(replace(Mystring,"s",""))
msgbox charcount

2.
suppose you have a string like
"God is Great"

A="God is Great"
Cnt=split(A,"G")
msgbox Ubound(Cnt)

3.
charcount=Len(mystring)-Len(replace(Mystring,"s",""))

What are the Challenges you faced while testing your Projects

Some of them were


1. time pressure and deadlines
2. late migration of components and DBs
3. requirements getting changed in the middle
4. patch migration without intimating
5. less experienced resources
6. large data in DB which increases the testing time
7. third party intervention - when some orders are made, onsite guys have to approve the orders
before proceeding with next application
8. defect rejection without even analysing the probs
9. some defects which feels hardto recreate
10. Finding critical test data -misbehaviour of system for a few types of test data.
11. Bugs closing taking its max time
12. n/w unavailability

ans face some more problems like


1.On-Yime delivers
2.Resource problem
3.Configure problems (like s/w,h/w and networking problems)

We have 10 page.In first page we 2 popup and next page we 3


popup window......(windows name is different)how can we
handle the all the popups without using recovery scenario

IF you are getting in different pages of same browser.


then you can use the following code:
Do While Browser("Logical name :=Property").Dialog
("ispopupwindow:=True").Exist
Browser("Logical name :=Property").Dialog
("ispopupwindow:=True").Close
Loop
You can use this as function and call this function in
every page

SystemUtil.CloseProcessByName "IEXPLORE"
'It will close all Browsers with all dependant popup
windows.

How to test menu options using qtp

Can you specify what exzactly u want to check in menu ?


Mostly we check wheter the menu option is exist or enable:
window("name").winmenu("name").exist(2)
OR
rc = window("name").winmenu("name").GetROProperty
("Enabled")
above command will return TRUE if menu is enabled elase
FALSE

Action1: I have a value "test" stored in a variable X.


I want to use that variable X in Action2 .. how?

Use environment variables.


Action 1 : Environment.Value("x")="test"
Value of x=Environment.Value("x") can be used any action.

I Scheduled a QTP Script on remote desktop. Script is going


to failure,when remote desktop connection fails.I have to
open my remote desktop untile the scripts exection
completes. If I disconnect my remote desktop connection,
script is going to fail. Could you please any assist in
this?
Do not close or minimise the remote desktop.
Go to Start - > run of machine on which u are running
scripts type "tscon 0 /dest:console" and press enter
this will disconnect the pc from ur end leaving the PC
unlocked and scripts will execute successfully
Small correction to the above answer
"tscon.exe 1/dest:console"
Put 1 inplace of 0. Its working fine for me.

How to call Datable values in the QTP program.


exp: I have two parameters like Email id and Password
this two i would like to add multiple entries in the datable
to use it.
What is the difference between Gobal/Action datatable

For multiple iteration we can use global data sheet.


Getting the value :Browser(" ").page(" ").webedit("Emailid"). set
datatable.value("Email id",dtGlobalSheet)
Browser(" ").page("
").webedit("Password")datatable.value("Password",dtGlobalSheet)
Global Sheet And Action Sheet
GlobalSheet :- Global sheet we can use for every action and
by default it run for multiple iteration depends on the
value in the global sheet.
Action Sheet :- Action sheet is for perticular action and by
default it runs only one iteration but we can change it to
run for multiple iteration depends on the value in the
action sheet from the action property.

Call DtValues in Qtp:(Ur data Present in Dt(Global/Action Sheet first u verify)


nd Then proceed with this script...
dim rc
rc=DataTable.GetSheet("Global/Action").GetRowCount
for i=1 to rc
Datatable.setCurrentRow(i)
invokeapplication "Give Flight appPath"

Dialog("Login").WinEdit("AgentName").set
DataTable("Email id","Global")
Dialog("Login").WinEdit("PWord").set
DataTable("Password","Global")
Dialog("Login").WinButton("OK").click
Window("FR").close
DataTable.SetNextRow
Next
Diff in Datatable:(As ur Req u can ...)
By Default Setting For Global sheet is:
Run For Multiple Iterations
By Default Setting For Action sheet is:
Run For One Iteration Only

datatable.rawvalue("emailid",dtglobalsheet)
datatable.rawvalue("password",actionsheet)
global represents the iteration of the test,

In QTP, Give the difference of Global sheet and Local sheet


in datatable?

There are two types of sheets in QTP, global sheet and


local sheet. in case if we are having more then one action
for a script, so we should use global sheet. because with
the help of this we can pass values to every individual
actions if we want. but local sheet is responsible and
relevant with only one action, with which it is associated.

n Qtp datatable there are 2 types of sheet Global sheet


and Local sheet
From global sheet we can pass values to any test or script
and from Local sheet we can pass values to current script
only

I have given u a application.To automate it what are the


things will u consider?

1. Consider requirements
2. As per requirement identify how much automation testing
required.
3. which part of the application need to automation testing.
4. Automation tool
4. Framework
5. Most important test plan which contains every details
about every activity of testing.

1.Do a feasibilty study.


2.Gather the rqmts u want to automate.
3.Then go for the diff tools that are availabily in market
4.take the rqmts ,do the obj identification with diff tools
and mark the percentage of object identified per rqmt vs
the tool used to identify.
5.Cost and licence of tool
6.availablity of technical experts and assistance of tool
support
7.timelines
8.Based on above guideliness ,analyze and then decide
whether u want to go for automating the proj or not...

1.when the application is stable we will go to automation.


2.Feasability study should done on the test cases.
3.feasability study should done on the Automation tools.
4.Estimations are placed.
5.Coding standerds should be define.
6.Framework should be define

I have a tool for automation testing (eg:qtp).I have two


functionality(A & B) to test.A is tested once in a year. B
is tested everyday. At present i have the money and resource
availability to automate only one functionality.Which one
will u suggest and why?

before automation,
consider for the ,whether we will be able to automate the
test case in the application
To know this....
firstly,we will consider the technical feasibilty for
automating tc then,the how many times the tc being executed
in entire automation suite,reusability of the test
functions and number of times the scripts need to be
executed in the future.then later on the time span,resource
avail,etc;;
so i would go for B
2.
we need to go for B why because we can write script in
notepad and save as .vbs file and add in schedule in
control panel everyday the process is going to
automated...

If 2 gmail browsers are opened in our system, how to enter


the mail id and password into second browser by using
discriptive program?

Browser("creationtime:=1","name:=Gmail").Page
("title:=Gmail").WebEdit("name:=Login").set "hihi"
i think the creation time should be 1 not 2.
why because creation Time starts from 0. (Please refer QTP
user manual )
Browser("index:=0","name:=Gmail").Page
("title:=Gmail").WebEdit("name:=Login").set "hihi"

Can we write class for vb script in Quick Test Professional?


Yes, Place the vb script in functions/procedures. Create a
new class and place the fun or procedures inside of the class.
create an instance for the class access the methods outside
as external source.

What is the difference between Mandatory and BaseFilter


Properies..

Mandatory properties,these are default properties to an object.

Base filter properties,the most fundamental properties of a particular test object class,whose values
cannot be changed.

Base filter properties:


The most fundamental properties (values given to the components at the time of creation of the
application) of a particular test object class, whose values cannot be changed without changing the
essence of the original object
Optional filter properties:
Other properties of an object that help to identify objects of a particular class as they cannot be changed
on a regular process, these object can be ignored if they are no longer in use

Smart Identification:
1. Basic Filter Properties:
Basic Filter Properties contains the most fundamental properties of a particular test object class;
those whose values cannot be changed without changing the essence of the original object.
<html tag>
1. Optional Filter Properties:
Optional Filter properties can help identifies object.
<name, type, html id, value etc>
If the usual object identification process fails QTP trigger Smart Identification (which is enabled
and check by default in QTP).
QTP identifies
1. Parent Object -> Page Object
2. Child Objects -> Web tables : Login
Web Edit: WebEdit {UserName,Password}
Web Buttons

QTP uses the Base Filter Object to reduce the object candidates list.

For example:- If micclass ->Web Button is only available.


Then, it uses Optional Filter properties to uniquely identify an object.
<input type= button value=Login>
This button is used for the Login.
<input type= button value=reset>
This button is used for the Reset.
! is used to test result in order to denote that Smart Identification was used.

How to find Total no of Text Fields in the Page..Anybody


please answer me..Thanks in Advance
Set oDesc = Description.Create()
oDesc("micclass").Value = "Text"
Set Lists = Browser("Login").Page("Application").Frame
("folderFrame").ChildObjects(oDesc)
NumberOfLists = Lists.Count()
msgbox NumberOfLists

set a = description.create
a("micclass").value = "webedit"
set ch_obj = browser("").page("").childobjects(a)
msgbox ch_obj.count

There is a table with 4 columns and 10 rows, how to write the


script to display the first column records using qtp? can
anybody help me with script?

rcnt=Browser().Page().webTable().rowcount
ccnt=Browser().Page().webTable().columncount(2)

for i=1 to rcnt


print Browser().page().webtable().getcellData(i,1)
next
(or)
for i=1 to rcnt
set obj=Browser().page().webtable().childItem
(i,1,"webElement",0)
print obj.getROproperty("text")
next

Suppose there is a bitmap with some text in it how do you


write the script to get the text

With quick test professional 9.2, you should try using Text
Area Checkpoint, which will extract the text out of the image.

by using the bimap check point u can ready the text inthe
bit map .

What is the difference between Systemutil.run and Navigate.

SystemUtil.Run opens any kind of application window or web.


Navigate will open web based application for a given URL

The InvokeApplication method can open only executable files


and is used primarily for backward compatibility.

SystemUtil.Run "http:\\gmail.com","open"
The Above Syntax will Launch a New Browser for "http:\\gmail.com"
Browser("abc").Navigate "http:\\gmail.com"
This one will launch "http:\\gmail.com" in an existing browser.
Navigate: Opens a specified URL in the browser. The InvokeApplication method can open only
executable files
Run any application from a specified location using a SystemUtil.Run statement

What is the difference between low level recording and


virtual object.
Low-Level Recordingenables you to record on any object in your application, whether or not
QuickTest recognizes the specific object or the specific operation. This mode records at the object
level and records all run-time objects as Window [Parent]or WinObject[child] test objects. Use lowlevel recording for recording in an environment or on an object not recognized by QuickTest.
Virtual Obj. Means.....
Application may contaion objects that behave like standard
objects but not recognize by QTP, u can define these
objects as a virtual objects and map them standard class.

Low Level Recording:


In Recording time QTP records "user actions with
respect to objects" along with "mouse coordinates" is
called Low Level Recording.
Virtual Object :
Some Times tools does not support the leatest

technologies to over come this draw back we use Virtual


Object Wizard.

There is web page with the webtable,this contains some data, how do you manipulate the
data.
we have two methods to get the data from webtable
1)getrowwithcelltext(we can get the rownum )
syntax:- Browser("micclass:=Browser").page
("micclass:=Page").WebTable("micclass:=WebTable","html
tag:=Table").getrowwithcelltext("text")
2)getcelldata
syntax:- Browser("micclass:=Browser").page
("micclass:=Page").WebTable("micclass:=WebTable","html
tag:=Table").getcelldata(rownum,colnum)

How many types of parameters are there in QTP and what are they?
You can use the parameter feature in QuickTest to enhance
your test or component by parameterizing the values that it
uses. A parameter is a variable that is assigned a value
from an external data source or generator.
You can parameterize values in steps and checkpoints in
your test or component. You can also parameterize the
values of action parameters.
If you wish to parameterize the same value in several steps
in your test or component, you may want to consider using
the Data Driver rather than adding parameters manually.

There are four types of parameters:


Test, action or component parameters enable you to use
values passed from your test or component, or values from
other actions in your test.
In order to use a value within a specific action, you must
pass the value down through the action hierarchy of your
test to the required action. You can then use that
parameter value to parameterize a step in your test or
component.
For example, suppose that you want to parameterize a step
in Action3 using a value that is passed into your test from
the external application that runs (calls) your test. You
can pass the value from the test level to Action1 (a toplevel action) to Action3 (a child action of Action1), and
then parameterize the required step using this Action input
parameter value (that was passed through from the external
application).
Data Table parameters enable you to create a data-driven
test (or action) that runs several times using the data you
supply. In each repetition, or iteration, QuickTest uses a
different value from the Data Table.
For example, suppose your application or Web site includes
a feature that enables users to search for contact
information from a membership database. When the user
enters a member's name, the member's contact information is
displayed, together with a button labelled View <MemName>'s
Picture, where <MemName> is the name of the member. You can
parameterize the name property of the button so that during
each iteration of the run session, QuickTest can identify
the different picture buttons.
Environment variable parameters enable you to use variable
values from other sources during the run session. These may
be values you supply, or values that QuickTest generates

for you based on conditions and options you choose.


For example, you can have QuickTest read all the values for
filling in a Web form from an external file, or you can use
one of QuickTest's built-in environment variables to insert
current information about the machine running the test or
component.
Random number parameters enable you to insert random
numbers as values in your test or component. For example,
to check how your application handles small and large
ticket orders, you can have QuickTest generate a random
number and insert it in a number of tickets edit field.

A parameter is avariable that is assigned a value from an


external data source or generator.You can parameterize
values in steps and checkpoints in your test or component.
You can also parameterize the values of action parameters.
There are four types of parameters:
1. Test, action or component parameters
2. Data Table parameters
3. Environment variable parameters
4. Random number parameters

Difference between object identification and smart identification


OBJECT IDENTIFICATION:
QTP will learn the information into the normal identification
1) fistful QTP will learn the information into the mandatory properties,it it think weather the properties
are satisfied or not,if it feel not sufficient,then it will try to idetify the objects in the first assistive
propetie ,once agait if it feel
sufficient ,if all the properties are sufficient and identify the objects unequally,once again if it is not
sufficient,if it learn the second assistive property , same process is continued.
SMART IDENTIFICATION:

QTP will learn all the mandatory properties,all the base filter properties,all the optional filter
properties.The bse filter&optiona filter properties are stored in secret place,will not to think them,it will
think the mandatory property is sufficient identefy the objects uniqually,if it will not satisfied ,it will
learn the second assistive properties and continue the process.

vb script for calling one function to the another function


se the command -> Call <Function Name>
Example:
Call DrawRectangle()
Call DrawTriangle()

ExecuteFile "File"
LoadFunctionLibrary "Path of File"

How to pass the parameter from one function to another


function in VB Scripting?

dim a
a=10
b=20
call value(a,b)
function value(a,b)
c = a+b
msgbox c

call val1(c)
end function
function val1(c)
d = c+2
msgbox d
end function

Kindly help me with the following queries..


-- How to recognize webtable using QTP and how to use it?
-- How would one conclude that it is a web table
-- For Example, if there is a web table and I am clicking on
say Cell A1, how would i know that i've clicked on cell A1
-- Kindly suggest me to use the web table better

To recognize web table using QTP you need to use SPY.


Using spy clieck somewhere inside you webtable.
you will get webelement and above that in hirarchy you will
get web table. Save this table in your object repository.
now do the coding like below
msgbox Browser("XXX").Page("XXX").WebTable
("XXX").getCellData(1,2)
here 1 is row number and 2 is column number

Extract a word from a sentenece?

Use the code below


varStr = "This is a sentence"
MyArray = Split(varStr," ")
i = ubound(MyArray)
For j=0 to i step 1
msgbox MyArray(j)
Next

strValue = "This is my World"


searchWord = "my"
arrWord = Split(strValue," ")
For iCount = 0 to UBound(arrWord)
If strComp(arrWord(iCount),searchWord,1) = 0 Then
Reporter.ReportEvent micPass, "Word
Found "&searchWord, "At Position "&iCount
Exit For
End If
Next

How will you set a unique four digit number in an edit field in QTP?
we can set 4 digit no in edit box field dynamically
----------------------------------------------------let assume password edit box is there
---------------------------------------str="rama"
no=randomnumber(1000,10000)'here we are generating random
value between 1000,10000

pwd=str&no
password=crypt.encrypt(pwd)
objectheirarchy.edit("password").setsecure pwd

where do you define the objects as regular expression when


u are using regular expressions.
There are situations when the Objects in the applications
are dynamic(having dynamic properties) and QTP fails to
recognize them. Such objects should be handles using
regular expressions.
We can define the objects using regular expression either
in the Object repository or in the code itself.
Example: the login page says" Welcome Mintu" in one login
and "Welcome guest" in another login. here we see that
Mintu and guest are two dynamic values. this needs to be
handled using regular expressions. say "Welcome .*"
here .* refers to any text appearing in the application.

How to find the OS name by using QTP script?


environment.value("OS")

example-date format is 01-jan-09 in QTP.How to convert this


format to 01-01-09?
val = "01-jan-09"
Conv_Val = cdate(val)
msgbox Conv_Val
Result : "01-01-2009"

please find below code


givenDate = "01-jan-09"
DD = Day(givenDate)
msgbox DD
MM= month(givenDate)
msgbox MM
YY=year(givenDate)
msgbox YY
sysdate=DD&"-"&MM&"-"&YY
msgbox sysdate

In Login two edit box which object class property value is


same, How to enter into 2nd edit box in qtp by vbscript.
using index property.
browser("x").page("x").webedit("y","index=1").set "abc"
' index 1 means first object which is left to right and top to bottom

How do function returns a value?How can we pass one function value to other function as
input
Function returns only one value. when we assign the final
value with variable that name should be the same name of
the function name.
In the given example, som is the function it returns the
sum of two values when we assign that value to variable[i.e
same as function name(example: som = c)]
if you don't assign, function doesn't return any value
(example: z = c)

Example:
Function som(a, b)
c=a+b
som = c '(instead of these two step we can write in single
step like som = a + b)
End Function
x = 10 + som(10, 20)
msgbox x
you can pass this value in any other function.
Example:
y = som(som(10, 20), x)
msgbox y

I want to open a text file and then search some specified


text in it and then replace that text with some other text
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\working\replace.txt",
ForWriting, True)
f.Write "QTP QTP RFT QTP QTP RFT QTP QTP"
Set f = fso.OpenTextFile("c:\working\replace.txt",
ForReading)
ReadAllTextFile = f.ReadAll
newText = Replace( ReadAllTextFile, "QTP", "QTPRO")
Set textFile = fso.OpenTextFile
( "C:\working\replace.txt", ForWriting )
textFile.WriteLine newText
f.Close

In simple terms "Filesystemobject" is an object model which


is used to handle the drives, folders, and files of a
system or server.
If an user needs to work Driver, Folder, Files properties,
methods or events then the first step he need to setup is
filesystemobject.

File System is used to create file through scripting.We can


read, write and save data in txt file and use it after
wards during testing. Here is example of creating txt file
through FSO
Const ForReading = 1, ForWriting = 2
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile("c:testfile.txt",
ForWriting, True)
MyFile.WriteLine "Hello world!"
MyFile.WriteLine "The quick brown fox"
MyFile.Close
Set MyFile = fso.OpenTextFile("c:testfile.txt",
ForReading)

ReadLineTextFile = MyFile.ReadLine ' Returns "Hello


world!"
It will create testfile.txt and enter "This is a test" in
that text file. You can later read that line "This is a
test" from this file while using
MyFile.ReadLine
We can save variables data during testing and then use that
data in future instances of testing and then delete that

103. Script to Compare Two Files

Public Function CompareFiles (F_Path_1, F_Path_2)


Dim FS, first_file, second_file
Set FS = CreateObject("Scripting.FileSystemObject")
'Function will simply exit if the size of both files being
compared is not equal
If FS.GetFile(F_Path_1).Size <> FS.GetFile(F_Path_2).Size
Then
CompareFiles = True
Exit Function
End If
'OpenAsTextStream Method: Opens a specified file and
returns
a TextStream object that can be used to read from, write
to,
or append to the file.

Set first_file = FS.GetFile(F_Path_1).OpenAsTextStream(1,

0)
Set second_file = FS.GetFile(F_Path_2).OpenAsTextStream(1,
0)
CompareFiles = False
'AtEndOfStream Property: Read-only property that returns
True
if the file pointer is at the end of a TextStream file;
False
if it is not.
Do While first_file.AtEndOfStream = False
'The Read method reads a specified number of characters
from
a TextStream file
Str1 = first_file.Read(1000)
Str2 = second_file.Read(1000)
'The StrComp function compares two strings and returns 0

if
the strings are equal

CompareFiles = StrComp(Str1, Str2, 0)


If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
first_file.Close()
second_file.Close()
End Function
File1 =inputbox ("Enter first file name e.g.
C:\Readme1.pdf")
File2 = inputbox ("Enter second file name e.g.
C:\Readme2.pdf")
If CompareFiles(File1, File2) = False Then

MsgBox File1 & " and " & File2 & " " &
Else
MsgBox File1 & " and " & File2 & " " &
End If

"are identical."
"are NOT identical."

Script through which Only One line in two files is compared

To find the specified string in Notepad using VB Scripting


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("N:/Wireline ECC.txt", 1)
line_num = 0
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
msgbox( strLine)
line_num = line_num+1
If instr(1,strLine,"Online")<> 0 Then
MyPos = instr(1,strLine,"Online")
Msgbox "Line No: " &line_num& " Position: "&MyPos
End If
Loop
objFile.Close
objFSO = nothing
objFile = nothing

HOW TO COUNT NUMBER OF ITEMS PRESENT IN WEB LIST

itemcount=Browser("browser name").page("page
name").weblist("web list name").GetRoproperty("items count")
msgbox itemcount
2.
using getitemscount method we can get how many items
present in the weblist

ex: a=window("name").wincombobox("name").getitemscount
msgbox a
3.
sRegKeys = Window("Registry Editor").WinListView
("SysListView32").GetContent

Below example illustrates how We can get the all items from the drop down in QTP.
arrWeblistItems = split(objParent.weblist("name:=listType").GetROProperty("all items"),";")
'print total number of items in the listbox
print arrWeblistItems.count
For itemCounter =0 to ubound(arrWeblistItems)
'print the value in the dropdown
print arrWeblistItems(itemCounter )
Next

How do we Access, retriew and edit the runtime objects in


Automation Testing using QTP

To access runtime objects we can use GETROProperty


and SETTOProperty to change the TESTOBJECT property in QTP.

We cannot edit runtime objects in Automation Testing, bcoz


Runtime objects means the Objects available in AUT,
we can only use the properties available for objects and we
can change the property/properties available in OR during
runtime by using SETTOPROPERTY
We can retrieve the property and its value by using
GetRoProperty

eg:
dialog("Login").Activate
dialog("Login").WinButton("OK").SetTOProperty "text","Cance"
print dialog("Login").WinButton("OK").GetROProperty("text")
it returns "Cance"
it is changing the property value during runtime.

How to load a object repository in QTP during runtime?


we can add object repository at runtime
Two ways are there u can add
1. when u write below syntax in Action1
Syntax: RepositoriesCollection.Add(Path)
Ex: RepositoriesCollection.Add(E:\OR\ObjRes.tsr)
if write in Action1 it will automatically add the Object
Respository to the Action1
(i.e Edit Menu-->Action-->Action Properties-->Associate
Repository tab) at runtime.
no need to add the object repository before running.
2. Add the object repository at runtime by using AOM
(Automated Object Model)
Ex:
Dim qtAppn
Dim qtObjRes
Set qtAppn = CreateObject("QuickTest.Application")

qtAppn.Launch
qtAppn.Visible = True
qtApp.Open "E:\Test\Test2", False, False
Set qtObjRes = qtApp.Test.Actions
("Login").ObjectRepositories
qtObjRes.Add "E:\OR\ObjRes.tsr", 1
The above example Add the Object Repository(ObjRes.tsr) to
the "Login" action in Test2

2. StrPath = "D:\FrameWork\Repository\GoogleHomePage.tsr"
RepositoriesCollection.Add(StrPath)

Can we add the function library directly from scripting in


qtp instead of adding from resource tab?

Set qtApp = CreateObject("QuickTest.Application")


qtApp.Launch
qtApp.Visible = True
qtApp.Open "C:\Tests\Test1", False, False
qtApp.Test.Settings.Resources.Libraries.Add "e:\Utils.vbs"

How to make arguments optional in a function?

See basically QTP does not support optional arguments but u


can achieve this with following ways1. You can pass NULL or Empty values
2. By using dictionary object

Can a function return a dictionary object?


Functions can return a dictonary object.
Dim dicObj
Set dicObj = CreateObject("Scripting.Dictionary")
Set obj=getname
MsgBox(obj.item("name"))

Public Function getname()


dicObj.add "name","Uday Kumar"
Set getname=dicObj
End function
How to retrive XML file data in QTP using Script ?
Const XMLDataFile = <your file path>
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)
Set nodes = xmlDoc.SelectNodes(<provide you node hierarchy>)
MsgBox "Total books: " & nodes.Length
Set nodes = xmlDoc.SelectNodes("<node hierarchy>/text()")
' get their values

For i = 0 To (nodes.Length - 1)
Title = nodes(i).NodeValue
MsgBox "Title #" & (i + 1) & ": " & Title
Next

several browsers opened. write QTP script to close all browsers except gmail.
Dim d
Set d=Description.Create
d("micclass").value="Browser"
Set a=Desktop.ChildObjects(d)
For i=0 to a.count-1
s=a(i).GetROProperty("title")
If instr(1,s,"Gmail")=0 Then
a(i).Close
End If
Next
If you want to close all browsers except gmail browser then you will follow this code.
set ObjDesk = Description.Creation
ObjDesk("micclass").Value="Browser"
set ObjDec =Desktop.ChildObjects(ObjDesk)
BroCount=ObjDec.Count
msgbox BroCount
if BroCount >0 then
for i=BroCount-1 to 0 step-1
if Instr(1,Browser("CreationTime=&i").GetRoproperty("name"),"gmail")=0 then
Browser("CreationTime:=&i").Close
End If
Next
End If
116. Script to Close all the Browser
Dim d
Set d=Description.Create
d("micclass").value="Browser"
Set a=Desktop.ChildObjects(d)

For i=0 to a.count-1


a(i).Close
End If
Next

Script to Close All browser except First Browser

Q: I have 10 files in a folder(say D:\). Out of which there


are some .txt, .xls, .doc. I want to know how to get the
count of each file using qtp?
set fso=createobject("scripting.filesystemobject")
set objfolder=fso.getfolder("XXX")
set fil=objfolder.files
for each fils in fil
fils1=fils1&fils.name
next
xls=split(fils1,".xls")
msgbox ubound(xls)
doc=split(fils1,".doc")
msgbox ubound(doc)
txt=split(fils1,".txt")
msgbox ubound(txt)

Dim filesys, demofolder, fil, filecoll, filist, ctr1, ctr2, ctr3


ctr1 = 0
ctr2 = 0
ctr3 = 0
Set filesys = CreateObject("Scripting.FileSystemObject")
Set demofolder = filesys.GetFolder("c:\QTPtest")
Set filecoll = demofolder.Files
For Each fil in filecoll
If filesys.getExtensionName("c:\QTPtest\" & fil.Name) =
"txt" Then

ctr1 = ctr1+1
End If
If filesys.getExtensionName("c:\QTPtest\" & fil.Name) =
"xls" Then
ctr2 = ctr2+1
End If
If filesys.getExtensionName("c:\QTPtest\" & fil.Name) =
"doc" Then
ctr3 = ctr3+1
End If
'filist = fil.name
'filist = filist & " "
Next
msgbox("The count for Text files is: " & ctr1 & " The count
for Excel files is: " & ctr2 &" The count for Word files
is: " & ctr3 )
Script to Count the Number of Browsers Opened
Set BrowserObj = Description.Create
BrowserObj("micclass").Value = "Browser"
Set Obj = Desktop.ChildObjects(BrowserObj)
Msgbox Obj.Count

IF there are seven browsers with same name open. I want to


close one particular browser thru QTP. how can i do this?
By Using Creation Time we will close particular browser. if
u open 7 browsers with same name but creation times r
different.
Ex:: browser("CreationTime:=7").close. if u want close 1
browser u can give no 1 ,

How do you export an output to a excel sheet?


Ex: I get my answer by using Msgbox"..." &R. How do I
displayed the result of the Msgbox (such as R) to an excel
sheet? Please let me know.Thanks

I think after capturing the run time value by using command


like x=window("").something.....getroproperty("text") then
do like Datable.export("path where u want to see the data")
set datatable.value(x,1)

We can capture the proprty of the message box throug


getroproperty("innertext").Pass this to a variable.After
that use MID function to retrieve 'R'.After that we can
create an external excel object and pass the value to that
sheet.

In web page there is five OK buttons available, while


recording i click on 3rd OK button, How QTP identify the 3rd
OK button while running script? Is qtp identify 3rd ok button?

QTP will recognise the ok button using index property


ex:browse(browser).page(page).webbutton
("name:=ok",index:=2").click

if devloper change only button names in present build then


script will execute or not , why? Only gui changed

If name is the only unique property for recognizing the


button then it will give error. But say if you have
different object identification property like html id. then
script will work without error.

It may or may not, depending on how that button was


initialy recognize. As question suggest only GUI is been
changed. So properties like button name, html id, html tag

will remain same. So if button was initialy uniqly


recognize using these property then it wil not giv error.

How do you use the parameters.input parameters and out put


parameters.
erisation means replacing a constatnt value with varaiable.
For example in calculator application u give value1 and
value2 and then click add.it gives value 3 as result.
so here we e to parameterize value1, value2 as input
parameters, value3 as output parameters

Generally we will pass data in b/w actions or to xternal


actions by using action parameters.Action parameters are of
2 types.
1)input parameters
2)output parameters
To see this we can follow below navigation:
step menu-->action properties-->click on parameter tab->here u will see two parameter tables resembling one to i/p
parameters and other to output parameters.

InputParameters and Output Parameters.... are available


in 'Actions' and also 'Functions'
Input Parameters: These are parameters passing from Calling
Action/Funtion to Called Action/Function... These values
can not be change in that Action/Function... (we can do
that in debug viewer pane using Command Tab)
Output Parameters: These are parameters we get from
Action/Function. They can be use out of the Action/Function
and use as we like (eg: input parameters for another
related Action/Function)
'Funtions return generally single value... but if you use

Output parameters we can use more than one value out of the
Function.
'Actions:
RunAction "ActionName",no.of iterations,i/pparmts,o/pparmts
'Functions
Function(i/pparameters,o/p parameters)
....
...
..
End Function
Call Function(i/pparameters,o/p parameters)

what are the environment variables,how do you use them.


give an example.

Environment Variables are variable whose value is fixed for


its usage everywhere.
There are two types.
1.Built in-which are already existing in QTP which we can
directly use in out script.
ex:ActionName,ActionIteration
2.User-defined
which user has to define and use those variables anywhere
in the action.
Ex:File path-Suppose u r reffering a data file in ur script
then store the location of ur file path in environment
variable and use it across the actions.

Wait
You can enter Exist and/or Wait statements to instruct QuickTest to wait for a window to open or an object
to appear. Exist statements return a boolean value indicating whether or not an object currently exists.

Wait statements instruct QuickTest to wait a specified amount of time before proceeding to the next step.
You can combine these statements within a loop to instruct QuickTest to wait until the object exists before
continuing with the test.
Wait statements instruct QuickTest to wait a specified amount of time before proceeding to the next step.
syntax: Wait(10)
Here the QTP will wait for 10 sec and after that it will proceed for the execution of the next step
Sync
Waits for the browser to complete the current navigation.
This method is only available for Web.This method can be used to synchronize the test execution with a
new web page that has to appear in the browser.

Difference Between Value & RawValue?


The raw value is the actual string written in a cell before
the cell has been computed, such as the actual text from a
formula.
Value property is used to set the value in the current row
of the Destination parameter (column) in the "ActionA" sheet
in the run-time Data Table.

QTP Datatable.RawValue
While you read from excel, cells which contain formula's like =Today(), =Date()
may not reflect the same text when you retreive them.
Workarounds
1. So you might change in the cells in Excel as follows:
=Text(TODAY())
2. use
vCellValue=Datatable.GetSheet("sheetname").getParameter("ColumnName").RAWVALUE

instead of
vCellValue=Datatable.GetSheet("sheetname").getParameter("ColumnName").VALUE

what is the script to select 2 or more than 2 options from


a listbox.

Browser().Page.().weblist().Select " "


Browser().Page.().weblist().Extendselect " "

What will be the test script in QTP to test a ComboBox


where a user has to select more than two items????
Function selectWebItem(webListName,ItemName,webItemIndexVal)
ClearDialogs()
strHandle = Window
("RegExpWndClass:=IEFrame","index:=0" ).GetROProperty
("hWnd")
Set gobjBrowser = Browser("hWnd:=" & strHandle)
Set gobjPage = gobjBrowser.Page("index:=1")
gobjPage.Sync
Set objDescription = Description.Create()
objDescription("Class Name").Value = "WebList"
objDescription("html tag").Value = "SELECT"
objDescription("name").Value = webListName

If gobjPage.WebList(objDescription).exist(0) Then
gobjPage.WebList(objDescription).select
ItemName
else
objDescription
("index").value=webItemIndexVal
If gobjPage.WebList(objDescription).exist
(0) Then
gobjPage.WebList
(objDescription).select ItemName

else
testPassCntr=testPassCntr+1
End if
End If
End Function

hy do we use both location and index identifier.


There are 3 types of ordinal identifiers available in qtp.
They are:
1) Location : qtp will create sequence of numbers from 0,
1, 2, 3. Based on the objects located on the application
or aut.
2) Index : qtp will create sequence of numbers from 0, 1,
2, 3. Based on the code implemented or developed for the
objects.
3) Creation Time :qtp will create sequence of numbers from
0, 1, 2, 3. Based on the loading time of the web pages

How to handle recovery scenario for a application


crash.write script for this.

QTP's Recovery Scenario Manager supports Handle for


Application Crash.
You can handle the application crash from "Recovery
Scenario Manager" by calling your own function call or go
with any of the given operation types like Keyboard and
Mouse Operation, Restart Windows, Close App Process.
To invoke Recovery Scenario Manager go to Resources ->
Recovery Scenario Manager.

By Using Trigger event, Recovery steps and Post recovery test run we can handle...
Trigger Event:-

Resources Menu --> Recovery Scenario Manager--> Click New--> Click Next -->Select Application
Crash as Trigger event-->Next -->Select selected executable application-->Next -->
post recovery test run:Select Recovery Operation {Keyboard, Mouse Operation,Close Application Process, function Call,
Restart, Microsoft Windows} -->Next -->If you want to check Add another operation else uncheck->Next -->Next -->Enter Scenario Name -->Next-->Select Option -->Finish -->Close -->Save the
scenario with .qrs

What is the difference between "call" and "callclose"

You can use two types of call statements to invoke one test
from another:
A call statement invokes a test from within another test.
A call_close statement invokes a test from within a script
and closes the test when the test is completed.
The call statement has the following syntax:
call test_name ( [ parameter 1, parameter 2, ...parameter
n ] );
The call_close statement has the following syntax:
call_close test_name ( [ parameter 1, parameter 2, ...
parameter n ] );
The test_name is the name of the test to invoke. The
parameters are the parameters defined for the called test.
The parameters are optional. However, when one test calls
another, the call statement should designate a value for
each parameter defined for the called test. If no
parameters are defined for the called test, the call
statement must contain an empty set of parentheses.

How to compare source and target database in testing?


Can anybody please tell me in detail the procedure how to
compare it?

use the database check point

suppose 3 excel sheets are there * we are trying to check


for login credentials for a page. userid from excel1 ,
password is from excel2 whether the page is opened or not
that checkpoint is result is should be stored in excel
3.... this qus i have faced in IBM technical round...
please tell script for above query

Getting User id from Excel 1


Set objxls = createobject("Excel.Application")
objxls.workbooks.open "C:\Documents and
Settings\ranantatmula\Desktop\data.xlsx"//path of the excel
sheet where user id is stored
v1 = objxls.cells(1,1) // where user id is stored in Excel
browser("xxx").page("yyy").webedit("username").set(v1)
Get PWD from excel 2
Set objxls1 = createobject("Excel.Application")
objxls.workbooks.open "C:\Documents and
Settings\ranantatmula\Desktop\data1.xlsx" //path of excel
where pwd is stored
v2 = objxls.cells(1,1) // where PWD id is stored in Excel
browser("xxx").page("yyy").webedit("username").set(v2)

To export the result in Excel 3


Set objxls3 = createobject("Excel.Application")
set objworkbook = objxls3.workbooks.Add

write a condition if page is opened


browser("xx").page("xx").webedit("userid").click
browser("xx").page("xx").webedit("pwd").click
browser("xx").page("xx").webbutton("submit").clcik

If page opens
objxls3.sheet(1).cells(1,1) = "PASS"
else
objxls3.sheet(1).cells(1,1) = "FAIL"
Endif

Is there any function or vbscript in QTP to clear the


cookies,sessions

webutil.DeleteCookies

You can write your own function also:


Public Sub MyDelCookies()
'Option Explicit
Dim strPath, WshNetwork, fso, objFol, objFile, var
strPath="c:\Documents and Settings\"
Set WshNetwork = CreateObject("WScript.network")
strPath=strPath + WshNetwork.UserName +"\Cookies"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder(strPath)
Set objFile = objFol.files
For Each var in objFile

If var.name<>"index.dat" Then
var.delete
End If
Next
Set WshNetwork=Nothing
Set fso=Nothing
End Sub

What is exact difference between while and do while in


QTP ?

The basic difference is in the time of checking the


condition during execution of loop. In while loop the
condition is checked at the start, if it is true then
statements enclosed in the loop structure are executed ,
otherwise the loop exits and control transfers to the
statements following this loop and this process continues
until the condition becomes false.
As:
While (condition)
{
statement1;
statement2;
.
.
}
Statements following the loop

But in the case of do-while loop condition is checked at


the end of structure (i.e., at least one time the
statements enclosed in this loop structure are executed
before checking the condition)
After executing the loop statements at least once, the loop
condition is checked; if it is true then the loop body is
executed again otherwise loop exits. As:
Do
{

statement1;
statement2;
.
.
}
While (condition)
Statements following the loop

I have 2 Environment variable which holds int. I called


into my test and addedup. but output is concatenating the
values instead of Sum. Ex. Envi("a")= 10, Envi("b") = 20,
c= Envi("a")+ Envi("b"). msgbox c ( Ans.1020). How to
overcome this pblm? I used the add fn also..

c= Cint(Envi("a"))+ Cint(Envi("b"))

Environment.Value("MyVariable")=10
A=Environment.Value("MyVariable")
Reporter.ReportEvent micPass, "The value of A: ", A
Environment.Value("MyVariable1")=20
B=Environment.Value("MyVariable1")
Reporter.ReportEvent micPass, "The value of B: ", B
C=A+B
msgbox C

Hi all im having a pop up validation browser which is 20 in


number, i want to close those similar pop browsers one after
the other, is there any specific code for that? i tried by
giving creation time & putting in a loop but it dint work?
valid working answers will be greatly appreciated

Definitely we can do it without writing the script through


Recovery Scenario.

In a Web appl, on a page, there are student names & details


listed.On clicking sort button,details are sorted on
Names.How do u verify htat sorting is done by using QTP?

you can use this function for comparing the values and if
your records are shown in webtable then you can use code
like this
in blank spaces between " " you have to pass your own
names
set hp=browser(" ").page(" ")
rc=browser(" ").page(" ").webtable(" ").rowcount
For i=2 to rc step 1
If i=rc Then
sone=hp.webtable(" ").getcelldata(i,1)
stwo=hp.webtable("html id:=dgList").getcelldata(i,1)
end if
sone=hp.webtable(" ").getcelldata(i,1)
stwo=hp.webtable(" ").getcelldata(i+1,1)
ret= CompareValues(sone, stwo)
'then on the basis of ret value you can verify that
list is sorted or not
'Using this function you can compare two values.
'Return values are based on three data types -Date,Numeric
or Text
'Return 1 if value1>value2 OR -1 if value1<value2, 0 if
value1=value2
Function CompareValues(sOne, sTwo) '--- as variant
On Error Resume Next
Dim im1,im2, iRtrn
if (isNumeric(Trim(sOne)) AND isNumeric(Trim(sTwo)))
then
im1 = CDbl(Trim(sOne))

im2 = CDbl(Trim(sTwo))
else
if (isDate(Trim(sOne)) AND isDate(Trim(sTwo))) then
im1 = CDate(Trim(sOne))
im2 = CDate(Trim(sTwo))
else
im1 = Trim(CSTR(sOne))
im2 = Trim(CSTR(sTwo))
end if
end if
iRtrn=0
If im1 < im2 then
iRtrn = -1
else
if im1 > im2 then
iRtrn = 1
end if
end if
CompareValues = iRtrn
If Err.Number > 0 then
strErrorMsg = "Error occured in function
CompareValues "
strErrorMsg = strErrorMsg & "Parameter
values passed to the function are: - ( " & sOne & ", " &
sTwo & ")"
Call ErrorHandler(strErrorMsg)
End If
End Function

What is the difference between Action and Function.? when


both has the same functionaltiy, when do we choose Action
and when do we choose Function..??

Actions are more specific to tool Example QTP


Functions are generic and part of programing language.

Actions in QTP are used to divide the test into different


logical units .
Within actions we can write functions .
but witin functions we cant use actions
we call functions in actions .

Major Differences:
Functions: Function returns only one value. it doesn't has
Object repository.
Actions: Actions has Object repository. It returns more
than one value (i.e Output parameters). We can declare
more than one Output parameter.
we can call Function in any Actions in QTP test. But Action
is not like that we have to mention that as reusable action
in Action Properties.
we can store Functions in .VBS file. but Action we cann't
store like this way.

How can we redirect QTP results in to a excel sheet after


the execution

By default it creates an XML file it displays the results

write the results in datatable & export the same

You have to create a function for that for example

Pass the below values


strTCNo=23 (Test Case No)
strResult=Pass (Result
public function FnTcStatus (strTCNo,strResult)

DtRwCnt= DataTable.GetSheet("Result").GetRowCount
For l=1 to DtRwCnt
DataTable.SetCurrentRow(l)
If DataTable("A","Result")=strTCNo Then
datatable.Value("TC_Status","Result")=uCase(strResult)&"_"&
Now()
End If
Next
strTcNo=""
strResult=""

end function

How to invoke QTP using Dos prompt ?

c:\Program Files\Mercury Interactive\QuickTest


Professional\bin\QTPro.exe

What is difference b/w


AOM,DOM,COM
Have u ever is used ny of the models.If so why?

AOM: Automated Object Model with this model we can create


QTP object. without opening QTP, we can do open Test, add
repositories, recovery scenarios, .vbs files, Datatable
(excels) etc.

DOM: Document Object Model this is come under HTML like


that. i have n't worked on this.
COM: Component Object Model with this model we can create
Excel, MS-Word, OutLook objects etc.
with this object we can do with out opening Excel
application, we can add sheet and count the rows and
columns etc.
like this way we can use these objects based on criteria

HOW do we find a datasheet when there are 4 datasheets in


data table.this question was asked by covansys interview.

DataTable.GetSheet(SheetID)
"SheetID" Variant Identifies the sheet to be returned.
The Sheet ID can be the sheet name or index. Index values
begin with 1.
to find the no of sheets in DataTable
"DataTable.GetSheetCount" method can be used

what is the difference between Automation object model(AOM)


and test object model(TOM)
COM - Component Object Model
(examples:- Excel objects, FSO objects)
DOM - Document Object Model
(examples:- Browser("").Page("").object.getElementsByTagName)
AOM - Automation Object Model
(examples:- Createobject("quicktest.application"))

TOM - Test Object Model


(examples:- concept how qtp manage AUT objects)

By using QTP automation object model, we can automate QTP


operations.
By using object, methods and properties provided by QTP, we
can write programs that can configure QTP operations and
settings.
For example, you can create and run an automation program
from Microsoft Visual Basic that loads the required add-ins
for a test or component, starts QuickTest in visible mode,
opens the test, configures settings that correspond to those
in the Options, Test Settings, and Record and Run Settings
dialog boxes, runs the test, and saves the test.
Test Object Model, is nothing but how QTP identifies the
objects in the application.
How to get the class of an object, what mandatory and
assistive properties are used during recording the
application, how it identifies the objects during run
session etc...

How to capture screen shots when an error occurs?

Objectheirarchy.CaptureBitmap "path"

n QTP8.2, we can choose the run settings


Test -> settings -> Run tab -> set ON save image of desktop
when error occurs checkbox
In QTP 9.2, follow the below navigation:
Tools -> Options -> Run tab -> In the drop down list box "On
Error"(default) is selected for "Save step screen capture
to results"
And even we can also configure, whether we have to proceed
to next step or stop the test execution by following below

navigation:
File Menu -> Settings -> Run Tab -> Choose the required
action from the "Whenever an error occurs during run
session" drop down list box.

Hi use RecoveryFunction to capture the image when error


ocours.
Step1: Create a VBS file using following founction
Function RecoveryFunction1(Object, Method, Arguments,
retVal)
'Find the Test Folder Path
Set qtApp = CreateObject("QuickTest.Application")
testpath = qtApp.Folders.item(1)
'stores the image inside the test folder
image_name= testpath &"\imagename.png"
Desktop.CaptureBitmap image_name
End Function
Step2: Go to Recovery manager
step3: select "On Any error" or select u r own option
Step4: select function to call
step5: call the above mentioned file
Rest QTP will do it for you

browser("").page("").webedit("").set"[email protected]"
browser("").page("").webedit("").set"fbnjvkjnbv"
browser("").page("").webbutton("signin").click
if browser("").page("").exist then
reporter.reportevent 0,"login","login is sucess"
else
browser("").page("").capturebitmap "b.bmp"
reporter.reportevent 1,"login","lgin is not sucess","b1.bmp"
end if
note->give the wrong psw ang you will get the result in
results window

How to export QTP results to an .xls file?

ataTable.Export("file path")
DataTable.ExportSheet("filepath","DTsheet")
DTsheet:index or name of the sheet which u want to export
to excel file.
Ex:
Datatable.Exportsheet("c:\name.xls","name")
Datatable.exportsheet("c:\name.xls",1)

what is qtp automation framework, what is the purpose of the


framework and which folders included in this framework pls
tell me with brief description

QTP Automation frame work is a process of doing automation.


here you need to create some folders and that is called
folder structure. the structure is as below
create an automation folder in one of the drives. and then
create the below folders in that.
Data,Library,scripts,recovery,results
we just store the input data in excel sheet and save it in
Data folder.
and the scripts in scripts folder
user defined functions in library folder
if u have an recoveries just save the .qrs files in
recovery folder
and if u want to store the results just export it to HTML
file and store it into results folder

Will QTP Support Japanese Language?


yes QTP support Japanese language because QTP identify objects on the basis of their properties
not by language, so it will support any type of language.

Whenever we want 2 test the Localization Testing.


QTP support Japanese and English languages.
But when u instal QTP.
U will select the Languages Option
Is it correct?

if there is a web table of having row and colmns.a button is


placed at 2nd row's 3rd column which is worked for both edit
and delete..how to write script for the button to test both
operation on the web table using desriptive programing..
plz help me on script wheather using getroproperty
Q2)what is the command for taking valiue from a web table in qtp

Using Descriptive Prograaming first identify the Properties


that are unique to recognize the webtable. After use
the 'ChildItem' method of webtable and create a Dynamic
object Model and then use the GetROProperty to fetch the
name of the button placed at 2nnd row and 3rd column.
Ex:
set objButton=Browser().page().frame().webtable().childitem
(2,3,"WebButton",0)
strname=objButton.getroproperty("name")
msgbox strname
The Above code Displays the name of the Button placed at
2nd row and 3rd column

Using Descriptive Prograaming first identify the Properties


that are unique to recognize the webtable. After use
the 'ChildItem' method of webtable and create a Dynamic
object Model and then use the GetROProperty to fetch the

name of the button placed at 2nnd row and 3rd column.


Ex:
set objButton=Browser().page().frame().webtable().childitem
(2,3,"WebButton",0)
strname=objButton.getroproperty("name")
msgbox strname
objButton.Set "Example" //For Webedit opertaion
objButton.Click //For Delete operation

For Ques 1
Browser().page().webtable().childitem
(2,3,"WebButton",0).Click
For Ques 2
strname=Browser().page().webtable().GetCellData(2,3)
msgbox strname

1.what is the difference between childobjects and child


items in qtp?
2.what is difference between a class and function?
3.can u convert ustimings to indian timings using vbscript?
4.i have scripts in one machine.can i run those scripts in
another machine.how?

1. Difference between Child Objects and Child Item


Child Objects return a collection of objects of a specific
type.
eg: for the count of No of webedits present in a page we
can use Child objects method
set odesc = Description.Create()
odesc("Class Name").Value = "WebEdit"
Browser("title:=.*").Page("title:=.*").ChildObjects("odesc")

Child Items can be used only with a webtable object type to


retrieve/access a test object from a cell in the webtable.

Child Objects is used to access the objects by using a desciption object. For example : To find out
the number of links.
Syntax: object.ChildObjects("Description")
Child item is used to access the objects without using a description object. For example : To click a
particular link in a specified row and column of a table.
Syntax: object.ChildItem(Row, Column, MicClass, Index)

write a vb script to calculate factorial of a number?

vf=1
vnum=inputbox("enter a no")
for i=2 to vnum
vf=vf*i
next
msgbox vf Dim n,f
n=inputbox("enter a number")
f=1
If n<0 Then
msgbox "invalid number"
else if n=0 or n=1 then
msgbox "the factorial of given number is : "& f
else
For i=1 to n
f=f*i
Next
msgbox "the factorial of given number is : "&f
End If
end if

How do you find out whether the string is Numeric or Alpha


numenric.Suppose..'QTP is an automation testing tool 12345'

How should I know it is alphanumeric.Can any one please


write the code for this

str = "QTP is an automation testing tool "


Dim ianRegEx
Set ianRegEx = New RegExp
ianRegEx.Pattern = "[a-z]+[\s]*[0-9]+"
ianRegEx.Global = True
ianRegEx.IgnoreCase = True
msgbox ianRegEx.Test(str)

a=array(1,5,6,3,10)
For i=0 to 4
For j=0 to 4
If a(i)<a(j) Then
t=a(i)
a(i)=a(j)
a(j)=t
End If
Next
Next
For i=0 to 4
print a(i)
Next

best way I found in case of your data sorting consists


of character and number, you may use Excel feature to
support this as following on:
'+++++++++++++++++++
Public Sub SCNYL_SortDataTest()
Const xlAscending = 1 'represents the sorting type 1 for

Ascending 2 for Desc


Const xlGuess = 0
Const xlTopToBottom = 1
Const xlSortNormal = 0
Const iCOLIDX_VALUE = 1 ' Set to Column "A"
Dim oExcel
Dim oWB
Dim oSheet
Dim oRange
Dim asInfo
Dim lRowIdx
Dim lMaxRows
Dim sColName
' Sample data
sValue = "eowos,bweoww, weoeos,ewsow,acc,bzaow,ceoes,
jaow, wwwowam, waosw, 1124,wowasdd, 56, 32,62,108"
' Classified to Array collection
asInfo = Split(sValue, ",")
' Refered to Excel Object
Set oExcel = CreateObject("Excel.Application")
' To make sure Excel Application already installed
If oExcel Is Nothing Then
' Clean Array Object
Erase asInfo
Exit Sub
End If
' Added a new the Workbook object
Set oWB = oExcel.Workbooks.Add
' Ignored all message window displays
oExcel.DisplayAlerts = False
Set oSheet = oWB.Worksheets(1)
' Get the Maximum of Array Object Boundary
lMaxRows = UBound(asInfo)
For lRowIdx = 0 To lMaxRows
' Loaded your data to Excel Sheet

oSheet.Cells(lRowIdx + 1, iCOLIDX_VALUE).Value =
Trim(asInfo(lRowIdx))
Next
' Set Excel Colum at "A"
sColName = "A1:A" & (lMaxRows+1)
oSheet.Range(sColName).Sort oSheet.Range("A1"),
xlAscending, , , , , , xlGuess, 1, False, xlTopToBottom, ,
xlSortNormal
' Clean Array Object
Erase asInfo
' If you'd like to array collection, you should
uncomment for the Array operation.
'ReDim Preserve asInfo(lMaxRows)
For lRowIdx = 0 To lMaxRows
With oSheet
'asInfo(lRowIdx) = .Cells(lRowIdx + 1,
iCOLIDX_VALUE).Value
Print .Cells(lRowIdx + 1,
iCOLIDX_VALUE).Value
End With
Next
' Not Save any thing for this Excel
With oWB
.Saved = False
.Close
End With
oExcel.Quit
' Restore memory allocation
Set oRange = Nothing
Set oWB = Nothing
Set oExcel = Nothing
'Erase asInfo
End Sub
'//// Main ////
Call SCNYL_SortDataTest()

What are the option displayed under debug view

Below are the tabs in Debug Viewer:


Watch Tab
This is used to view the value of any variable or an expression in the test. To add an
expression, Click the expression and choose Debug > Add to Watch.

Variables Tab
QTP automatically displays the current value of all variables in the current action or function in the
Variables tabup to the point where the test or function library is stopped or paused. We can
change value of a variable manually also in variables tab. This will be reflected in test.

Command tab
This is to execute a line of script to set or modify the current value of a variable or VBScript object in
your test or function library.

difference between step into and step over and step out in qtp

161

in a webapplication a webeditbox is not allowing 'copy paste' option. you are supposed to
enter values with key press how to enter the values using qtp

There are three ways to use keyboard input in QuickTest Professional and Unified Functional
Testing: Type, SendKeys and Device Replay

SwfObject(swfname:=Blank).Type micTab
SwfObject("swfname:=Blank").Type micCtrlDwn + micShiftDwn + "L" + micShiftUp +
micCtrlUp
SwfObject(swfname:=Blank).Type This is my string

Dim mySendKeys
set mySendKeys = CreateObject("WScript.shell")
mySendKeys.SendKeys({TAB})

*A few important tips: Unlike the QTP TYPE method, you will need to use curly braces for
arguments like a TAB or Up arrow key strokes. Also SendKeys has the following special
characters: Alt(%), Ctrl(^), Shift(+) and Enter(~) keys

So, to send a CTRL and press the A key you would send:
mySendKeys.SendKeys("^A")

create a Device Replay object.


Dim myDeviceReplay
Set myDeviceReplay = CreateObject("Mercury.DeviceReplay")
myDeviceReplay.PressKey 15

From The HP knowledge base:

The functions that can be used with the Device Replay object are (all
coordinates are relative to the top left corner of the screen):
Function

Description

MouseMove x, y

Move the mouse to the screen coordinate


(x,y).

MouseClick x, y, button

Move the mouse to the screen coordinate


(x,y) and click the button
(0=left; 1=middle; 2=right).

MouseDblClick x, y, button

Move the mouse to the screen coordinate


(x,y) and double-click the button
(0=left; 1=middle; 2=right).

DragAndDrop x, y, dropx,
dropy, button

Drag the mouse from screen coordinate


(x,y) to (dropx,dropy) with the button
(0=left; 1=middle; 2=right) pressed.

PressKey key

Press a key using the ASCII code of the


key.
For example, Chr(13), vbCR and vbTab.

MouseDown x, y, button

Press the mouse button on screen


coordinate (x,y).

MouseUp x, y, button

Release the mouse button on screen


coordinate (x,y).

KeyDown key

Press a key using the ASCII code of the


key.
For example, Chr(13), vbCR and vbTab.

KeyUp key

Release a key using the ASCII code of the


key.

For example, Chr(13), vbCR and vbTab.


SendString string

Type a string.

There is one parent browser and 'n' number of child browsers


on desktop. Write a code to close all the child browsers but
parent browser should not be closed.
Open a new Browser
SystemUtil.Run iexplore.exe, http://www.google.com
Browser Sync
Browser(CreationTime:=0).Sync
Find total number of tabs in the browser window
iTabs = Browser(CreationTime:=0).GetROProperty(number of tabs)
msgbox iTabs Displays the value 1
Open a new tab within the same browser
Browser(CreationTime:=0).OpenNewTab()
Sync for new tab
Browser(CreationTime:=1).Sync
Load some web page in the new tab
Browser(CreationTime:=1).Navigate http://www.yahoo.com
Find total number of tabs in the browser window
iTabs = Browser(CreationTime:=0).GetROProperty(number of tabs)
msgbox iTabs Displays the value 2
Close all the tabs in the browser window
Browser(CreationTime:=0).CloseAllTabs()
OR -> Browser(CreationTime:=1).CloseAllTabs()
Now, you can use Browser(CreationTime:=1) to work on the second tab. Hope this helps you.
Thanks,

165

Write VB script to test given number is Prime Number

Dim n
count=0
n=inputbox("enter a number")
For i=2 to n-1
If n mod i=0Then
count=count+1
End If
Next
If count>3 Then
print "given numer is normal number"
else
print "given number is prime number"
End If

How to find duplicates in an array and remove them


efficiently?

Dim a(4)
a(0) = 1
a(1) = 4
a(2) = 5
a(3) = 4
a(4) = 5
For i = ubound(a)-1 to 0 step - 1
For j=0 to i
If a(j) = a(j+1) Then
a(j) = empty
ElseIf a(j)>a(j+1) Then
temp = a(j+1)
a(j+1) = a(j)
a(j) = temp
End If
Next
Next
For i=0 to ubound(a)

print a(i)
Next

There is an array 1-100 integers randomly arrandged.one integer missing,find it effectnly?


Method

1)

(Use

Sort

Sorting)

the

input

array.

count

array)

2) Traverse the array and check for missing and repeating.


Time Complexity: O(nLogn)
Thanks to LoneShadow for suggesting this method.
Method
1)

Create

2)

Traverse

a)

temp
the

(Use
array

input

temp[]
array

if(temp[arr[i]]

b)

if(temp[arr[i]]

of

size

arr[],

with

and

==
==

do

0)
1)

all

initial

following

values
for

temp[arr[i]]
output

as

each
=

arr[i]

0.
arr[i]
1;

//repeating

3) Traverse temp[] and output the array element having value as 0 (This is the missing element)
Time

Complexity:

O(n)

Auxiliary Space: O(n)


Method

(Use

elements

as

Index

and

mark

the

visited

places)

Traverse the array. While traversing, use absolute value of every element as index and make the value at
this index as negative to mark it visited. If something is already marked negative then this is the repeating
element. To find missing, traverse the array again and look for a positive value.
#include<stdio.h>
#include<stdlib.h>

void printTwoElements(int arr[], int size)


{
int i;
printf("\n The repeating element is");

for(i = 0; i < size; i++)


{
if(arr[abs(arr[i])-1] > 0)
arr[abs(arr[i])-1] = -arr[abs(arr[i])-1];
else
printf(" %d ", abs(arr[i]));
}

printf("\nand the missing element is ");


for(i=0; i<size; i++)
{
if(arr[i]>0)
printf("%d",i+1);
}
}

/* Driver program to test above function */


int main()
{
int arr[] = {7, 3, 4, 5, 5, 6, 2};
int n = sizeof(arr)/sizeof(arr[0]);
printTwoElements(arr, n);
return 0;
}
Run on IDE
Time Complexity: O(n)
Thanks to Manish Mishra for suggesting this method.

Method

(Make

two

equations)

Let x be the missing and y be the repeating element.


1)

Get

Sum

of

sum

array

2)

computed

Get

Product

of

of
S

product
array

computed

all
n(n+1)/2

of
P

numbers.

all
1*2*3**n

numbers.
*

3) The above two steps give us two equations, we can solve the equations and get the values of x and y.
Time Complexity: O(n)
Thanks to disappearedng for suggesting this solution.
This method can cause arithmetic overflow as we calculate product and sum of all array elements.
See this for changes suggested by john to reduce the chances of overflow.
Method
Let

5
x

and

(Use
be

the

desired

XOR)
output

elements.

Calculate XOR of all the array elements.


xor1 = arr[0]^arr[1]^arr[2].....arr[n-1]

XOR the result with all numbers from 1 to n


xor1 = xor1^1^2^.....^n

In the result xor1, all elements would nullify each other except x and y. All the bits that are set in xor1 will
be set in either x or y. So if we take any set bit (We have chosen the rightmost set bit in code) of xor1 and
divide the elements of the array in two sets one set of elements with same bit set and other set with
same bit not set. By doing so, we will get x in one set and y in another set. Now if we do XOR of all the
elements in first set, we will get x, and by doing same in other set we will get y.
#include <stdio.h>
#include <stdlib.h>

/* The output of this function is stored at *x and *y */


void getTwoElements(int arr[], int n, int *x, int *y)

{
int xor1;

/* Will hold xor of all elements and numbers from 1 to n */

int set_bit_no;

/* Will have only single set bit of xor1 */

int i;
*x = 0;
*y = 0;

xor1 = arr[0];

/* Get the xor of all array elements elements */


for(i = 1; i < n; i++)
xor1 = xor1^arr[i];

/* XOR the previous result with numbers from 1 to n*/


for(i = 1; i <= n; i++)
xor1 = xor1^i;

/* Get the rightmost set bit in set_bit_no */


set_bit_no = xor1 & ~(xor1-1);

/* Now divide elements in two sets by comparing rightmost set


bit of xor1 with bit at same position in each element. Also, get XORs
of two sets. The two XORs are the output elements.
The following two for loops serve the purpose */
for(i = 0; i < n; i++)
{
if(arr[i] & set_bit_no)

*x = *x ^ arr[i]; /* arr[i] belongs to first set */


else
*y = *y ^ arr[i]; /* arr[i] belongs to second set*/
}
for(i = 1; i <= n; i++)
{
if(i & set_bit_no)
*x = *x ^ i; /* i belongs to first set */
else
*y = *y ^ i; /* i belongs to second set*/
}

/* Now *x and *y hold the desired output elements */


}

/* Driver program to test above function */


int main()
{
int arr[] = {1, 3, 4, 5, 5, 6, 2};
int *x = (int *)malloc(sizeof(int));
int *y = (int *)malloc(sizeof(int));
int n = sizeof(arr)/sizeof(arr[0]);
getTwoElements(arr, n, x, y);
printf(" The two elements are %d and %d", *x, *y);
getchar();
}
Run on IDE
Time Complexity: O(n)

A webTable has a link how to click?


set a = Browser("B").Page("P").WebTable("WT:").ChildItem(1, 1, "Link", 2)

"2" denotes the 2nd link in a same sell

Regular expression usage in qtp


A regular expression is a string that describes or matches a set of strings. It is often called
apattern as it describes set of strings. In this article we are going to discuss about using Regular
expressions in VB Script/QTP.

Regular Expressions enable Quick Test to identify objects and text strings with varying
values.Regular
expressions
are
used
when
the
objects
value
is
dynamically
changed.
A regular expression is a string that specifies a complex search phrase. By using
special
characters
such
as
a
period
(.),
asterisk (*), caret (^), and brackets ([ ]), etc. you define the conditions of the search.

Steps to Specify Regular Expressions for an object in Object Repository:


1.

Go

to

2.

Select

3.

In

4.

Select

Object
the

the

Object

right
the

Repository.

side

property

Navigation:

Resources>>Object

which

you

want

to

you

can

observe

which

you

want

to

specify

regular

properties

of

specify

regular

Repository.
expression.
that

object.

expression.

5. Click on the property value of that property and the property value is editable. There
is
a
configure
button
appeared
with
the
symbol
<#>
6.
7.

Click on the configure button or use Ctrl+F11 to open configure window.


Select

Regular

Expression

check

box.

a. If the property value is having any special characters then QTP will display a dialog
with
asking
Do you want to add the backslash (\) before each special character in order to treat
it
literally?
b. If you click on yes QTP will automatically gives the backslash before every special
character.
So
that
the
special
characters will
be
treated
as literal.
8.
9.

Now

specify

the

regular

expression

Click

in

constant

edit

on

box.
OK.

10. Observe that a symbol A.* is added in property field. This means, that property is
using
regular
expression.
11. Highlight the object in application to ensure that the provided regular expression is
working
fine.

In Dynamic descriptive programming we create a descriptive object using


description.create.
While specifying properties we can give regular expressions. By default the properties
will be treated as regular expression when you added to description object.
Set oDescription=Description.Create
oDescription("micclass").value= "Browser"
oDescription("openurl").value= "http://www.google.co.in"

Here in this URL property there are three dots (.) which can be treated as regular
expressions. These dots will work as regular expressions because by default the
property values will be treated as regular expressions.
There is a property called regularexpression for description object which is used to set
the property values to work as regular expressions or as a literal string values.
In the Above example, set the regularexpression
treat "http://www.google.co.in" as a literal string.
Set oDescription=Description.Create
oDescription("micclass").value= "Browser"
oDescription("openurl").value= "http://www.google.co.in"
oDescription("openurl").regularexpression = False

property

to

false

to

oDescription("openurl").regularexpression = False

Note:
You can always use forward slash symbol (\) before every special character to treat a
property
value
as
literal
character.

Use

of

We

can

Regular
use

regular

1. Defining

Properties

2. Verifying

data

3. Parameterize

an

Expression
expressions

in

of

QTP

QTP
an

using
object

in

Object

check

property

when

points

or

check

values

of

point

Note:

You

can

use

regular

expressions

only

for

type

string.

By default all properties which you pass from object property are strings / Constants.
When using action parameters to parameterize a check point or an object repository,
those
action
parameters
data
type
must be string type. If you specify any other data type, that will not be treated as
regular
expression.
We can assign property values to variables in QTP when using descriptive
programming.
When
assigning
regular
expression to any variable make sure that regular expression is in string format.
When any special character in a regular expression is preceded by a backslash (\),
QuickTest
searches
for
the
literal
character.
If your searching for a character * in a string, then you need to give the pattern as
\*

Defining

Properties

for

an

Object

using

Regular

Expressions

If you expect any change in the object property value at run session, Regular
Expressions are useful to handle that dynamic change of the property value.
Example:
If you login to gmail.com, the browser title will be Gmail Inbox MailID
Gmail Inbox [email protected]
Here Inbox is the selected folder name in Gmail and MailID is login user mail id.
These two are not constants. If you select sent mail folder immediately the browser
title will be changed. In this case you may get object identification problems if youre
using the name property for the browser object. To overcome this dynamic change in
the application we need to use regular expression in object properties. For this you have
to use Gmail - .* -.*@gmail\.com as a Regular Expression.
Like this if you expect any object property is dynamic you can use regular expressions
as required.

How to check the value for variables during run time


Put a Break point then
do F11 step .
when u comes to variable,select that variable
and do Watch(ctrl+T).In this way during run time
u can chck value of variable.

You can achieve this only when you debug the scripts.
Put some break points in your script.
By default the runtime evaluates the variable values upto
that breakpoint, and from there on to know var. values use
step in, step out short cut keys.

To see runtime value of a particular object or variable,

- Set a break point in script at object/variable you want to see the value.
Select the variable or object --> right click --> select "Add to watch".
- Then the value will be displayed in Debug viewer window.
A VBScript function to convert Local Time to UTC/GMT Time
Function Convert_to_GMT()
Dim var_offset
Dim WshShell
set WshShell = WScript.CreateObject("WScript.Shell")
var_offset, return value from ActiveTimeBias, is in minutes
var_offset = WshShell.RegRead("HKLM\System\CurrentControlSet\Control
\TimeZoneInformation\ActiveTimeBias")
Taking current date/time and adding to var_offset because UTC = local time + bias
Convert_to_GMT = DateAdd("n", var_offset, Now())
Msgbox (Convert_to_GMT)
End Function
Calling function
Convert_to_GMT()
Many people do get confuse between UTC and GMT. Actually UTC and GMT is one and the
same thing [Link].
You can check whether this function is returning the correct value by visiting World Time
Server.

can u convert US time to india time in qtp


script for number

pattern programs in VBScript? UFT/QTP.

For i = 1 to 10
Yoga1 = Yoga1 & i
Print Yoga1
Next

Output:
1
12
123

1234
12345
123456
1234567
12345678
123456789
12345678910

For i = 5 To 1 Step -1
For j = 1 To i
Yoga2 = Yoga2 & j
Next
Print Yoga2
Yoga2 = ""
Next

Output:
12345
1234
123
12
1

In an application you have a web table. You are provided


with an external Excel sheet with the same structure as that
of the web table.

How will you retrieve all data from the web table and
compare it with corresponding data available in the excel
sheet, using QTP?
How will you report the results in QTP?

'Get the Web Table Row and Col count using the GetROProperty
rowcount=
Browser("").Page("").WebTable("").GetRoProperty("rows")
colcount=
Browser("").Page("").WebTable("").GetRoProperty("cols")
'Create a Excel COM object to read the data from the file.
Set excelobj=CreateObject("Excel.Application")
Set excelbooks=excelobj.Workbooks.open("C:\Data-excel.xls")
Set excelsheets=excelobj.Worksheets.item("Sheet1")
'Now loop through the excel and the wettable and check their
values
for i=0 to rowcount
for j=0 to colcount
if (
Browser("").Page("").WebTable("").GetCellData(i,j)=excelsheets.Cells(i,j))
Then
Reporter.ReportEvent micPass ,"Validation","Cell values & i
& j are same"
Else
Reporter.ReportEvent micFail ,"Validation","Cell values & i
& j do not match"
End If
Next
Next

Can I import a excel sheet in Action1 datatable? How?


datatable.importsheet"path of excel","excell sheet name","action id(or)action name"
datatable.importsheet"d:\data.xls","sheet1","Action1"

for ex:datatable.importsheet("c:\products.xls","sheet1",2)
hear 2 means: action sheet id

Timer
The Timer function returns the number of seconds that have passed since midnight
(12:00:00 AM).
Msgbox(Timer)
Shows 86296.13 at 11:58:16 PM

How do i find CSV file type

Please find the code which will identify the csv or xls/xlsx files in a folder.
Dim xl,fldr,noOfFiles,fileName1,token,fileNameArr
Set xl = CreateObject("scripting.filesystemobject")
set fldr = xl.GetFolder("C:\Documents and Settings\Temp\Desktop\Folder").Files ''replace
the path of the folder
noOfFiles = fldr.Count
MsgBox noOfFiles
For each token in fldr
fileName1 = token.name
fileNameArr = split(fileName1,".")
If UCase(fileNameArr(ubound(fileNameArr))) = "CSV" Then
reporter.ReportEvent micPass,"This is a CSV file: "&amp;fileName1,"CSV"
Elseif UCase(fileNameArr(ubound(fileNameArr))) = "XLS" or
UCase(fileNameArr(ubound(fileNameArr))) = "XLSX" then
reporter.ReportEvent micPass,"This is an Excel file:"&amp;fileName1,"Excel"
Else
reporter.ReportEvent micFail,"This is not CSV or Excel file:"&amp;fileName1,"Error"
End If

next

What do you do if QTP doesn't recognize object ,what action


should be taken
QTP does not recognize the object means, you dont have
proper add-ins. In this case, QTP treats the objects as nonstandard objects. We can map these non-standard objects to
standard objects by using virtual object wizard. Once
mapped sucessfully, QTP can identify the objects.

1)one is Using Virtual Object wizard Qtp,QTP does not


recognize the object means, you dont have
proper add-ins. In this case, QTP treats the objects as nonstandard objects.
2)go with low-level recording.
3)one is Smart Identification .

Did you find anything in your project that QTP proved inefficient to perform?
yes,In my project QTP proved inefficient to perform GUI testing of the application.

How we can do Batch testing in QTP?

A special tool s add wis Qtp In QTP tool


not like Win Runner
1.goto Tool/OPtion/Run
2.Click on checkbox{Alow other..}
Apply
3.goto Start Menu/Prog/Qtp/Tool/Testbatch Run
Batch/Add

select script and open dat u wana run


Goto Batch?run

First we record tests and save that tests with unique name
after that we go to srart->Programs->QTPtool->Batch testing> selectTest batch runner one window is opened in that
window we click on Browse button asked the path of the test
we give the path of the first test after click add button
follo above navigation at the of the all tests.after that
we run the test.Endstate of one test is basestate of
another test.

By Using Test Batch runner which available with QTP


tools.just open it add the required actions to that window
then say run. it will run the actions which u have added to
that.

How to retrieve data from application objects?

Using Loop Statements and GetROProperty Method

Capturing Values From An Application Objects


January 8, 2009 4:01 AM

Checkpoints and validations can be done by capturing actual values from an object in the Application
and then comparing that value with some predefined value. QTP provides various methods for
capturing values from an Application object. We will discuss all of these methods in detail.
Checkpoints
Checkpoints can be used for validating an Actual value against Expected value. A Checkpoints can
capture and compare multiple values. One problem with capturing values using Checkpoints is that the
capture values are not visible at run-time, they can only be viewed in the test results summary.

Thought it is possible to capture the final result of the Checkpoint and see if it passed or failed. The
code shown below demonstrated how to capture the result of a checkpont

Visual Basic
1 Dim bPassed
2 bPassed = Browser("X").Page("X").WebEdit("X").Check ( CheckPoint("Y") )
3
4 If bPassed Then
5

Msbox "Passed"

6 End if

Note that we have used parenthesis before and after CheckPoint(Y), this is required when we want
to capture the value returned from Check method. If the return value is not to be capture and only
the Checkpoint needs to executed we can use Browser(X).Page(X).WebEdit(X).Check
CheckPoint(Y)
Output Value
Output Value is used to extract property value from object and store it in DataTable or Environment
variable. Consider a Checkpoint txtTest which extracts the value of html tag and value of a text
box into the Global DataTable. Example of an Output Value is shown below
Browser(X).Page(X).WebEdit(txtTest).Output CheckPoint(txtTest)
Running the above code will output value of the html tag and value property into the DataTable.
GetROProperty
GetROProperty method can be used to fetch property values for an object. The txtTest Checkpoint
we used earlier can be simulated using GetROProperty as shown in the code below

Visual Basic
DataTable("txtTest_html_tag_out", dtGlobalSheet) =
1 Browser("X").Page("X").WebEdit("txtTest").GetROProperty("html tag")
2 DataTable("txtTest_value_out", dtGlobalSheet) =
Browser("X").Page("X").WebEdit("txtTest").GetROProperty("value")

Using GetROProperty makes things more flexible when compared with Output Values. Output Value
can only fetch the values into DataTable or Environment, on the other we can use GetROProperty to
fetch data in any variable or data storage holder.
Which method to use?
When it comes to choosing the best method for capturing values, i vote for GetROProperty for the
following reasons

Checkpoints cant be used to capture values at run-time

Output Value cant be modified at run-time i.e. we cant add or remove a property from a
Ouput Value

Output Value limits fetching the data into DataTable or Environment Variables only

Output Value gets stored within the Object Repository and is not visible in QTP 9.2 or
lower

Output Value cant be directly added to a Shared Object Repository

Output Value cant be created dynamically at run-time

How to load user defined environment variables from file to QTP manually and dynamically?
Steps:
1. Create file named qtp.xml and write it in a following format and save it in c directory.

Load and Export User defined environment variables in QTP :


2. Go to File->setting->Environment tab.
3. select variable type to User-defined.
4. check Load variables and values from external file named box.
5. enter file name and path for e.g here c:\qtp.xml
6. Press apply and ok.
Now Lets talk about how to load it dynamically. You need to do following things.

1. Create one XML file described in above first step.


2. Write following line in your test script.
environment.LoadFromFile(c:\qtp.xml)
msgbox environment.Value(qtp)
After running above code You will have one message box with this contenthttp://quicklearnqtp.blogspot.com/.
How to export user defined environment variables to any XML file manually and dynamically.
Steps:
1. Go to File->setting->Environment tab.
2. Select variable type to User-defined.
3. Press on Export button and give the name of file for e.g qtptest.xml
You will see all the user defined variable will be exported to qtptest.xml file( In XML format).
Now Lets talk about how to export variables to any XML file it dynamically/programmatically. You need to do
following things.
Write following line in your test script.
environment.ExternalFileName(c:\qtptest.xml)

All user defined environment variables will be exported to qtptest.xml file.


Note: If you dont have any user-defined variable stored in QTP. Than error will occur.
ExternalFileName Property
Description
Returns the name of the loaded external environment variable file specified in the Environment pane
of the Test Settings dialog box. If no external environment variable file is loaded, returns
an emptystring.
It doesnt facilitate exporting of environment variables

How to load vbs during runtime?


Loading function libraries at runtime was introduced in QTP-11. This feature enables
loading of libraries when step runs instead of at the beginning of Run session.

This is helpful incase you need only particular set of function libraries based on
the environment of AUT.
For example:- we are doing localization testing of our AUT, so instead of associating all the
function libraries to the test, we'll use only required set of libraries based on localization of
AUT and that will be added at the run time.

Syntax:LoadFunctionLibrary (Path of the function library)

Example:'Loading function libaries based on the localization of AUT


Dim sLocal
'Tkaing value of AUT Enviornment from Datatable or external database
sLocal= DataTable("Enviornment_AUT",1)
'Based on the enviornment concerned library will be laoded at runtime
If sLocal="Dutch" Then
LoadFunctionLibrary("C:\Functions\Dutch.qfl")
Else
LoadFunctionLibrary("C:\Functions\English.qfl")
End If
Important:

As we are adding this at Runtime, so it wont be visible in


Resources,Missing Resources,To do panes

Performance of UFT can be affected as Function libraries are getting


loaded at Runtime

At the end of Run, all the dynamically loaded libraries are unloaded.

Incase function Name is same inthe associated and dynmically


loaded libray than Dynamically loaded function will be given
preference

Another way of loading libraries at runtime is using "ExecuteFile"


statement in vbscript.

ExecuteFile "C:\Functions.vbs" (Now all the functions inside this file


are available for usage in the script)

Email ThisBlogThis!Share to TwitterShare to Facebook

How to load XMLdring runtime?


LoadFromFile Method :
Loads the specified environment variable file. The environment variable file must be an XML file using the
following syntax:

<Environment>
<Variable>
<Name>This is the first variable's name</Name>
<Value>This is the first variable's value</Value>
</Variable>
</Environment>
Syntax :
Environment.LoadFromFile(Path)
Path : The path of the environment file to load.
Example :
Environment.LoadFromFile("C:\QuickTest\Files\MyVariables.xml")

where will you store the url of the application in ,as a tester we need to test in different
envronments.so the URL of the AUT wil keep changing accordingly,where will u store the URL of
the application?
In Environment variable
'####################################
'Ways to Return values from Function
'####################################
'a. Single return value
Function Temp()

Dim x
X=5
Temp= x
End Function
'b.Multiple values return:
Concatenate variables
Function Temp()
Dim x,y
X=5
Y=6
Temp= x & "~"y
End Function
'c. Save Variables in array
Function Temp()
Dim x,y, aResult(1)
x=5
y=6
aResult (0) = x
aResult(1) = y
Temp=aResult
End Function
'd. Return Object
Set ret = Temp()
X = ret.Item(1)
Y= ret.item(2)
Function Temp()
Dim oDict,x,y
X=5
Y=8
Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add 1,x
oDict.Add 2,y
Set Temp= oDict
End Function
'e. Return Multiple values of different Types:
ret = Temp()
ret_1 = ret(0)
ret_2= ret(1)
ret_3 = ret(2)
Set ret_4 = ret(3)

msgbox
msgbox
msgbox
msgbox

ret_1
ret_2
ret_3
ret_4.FileExists("C:\QueryRandD.txt")

'Output:
'5, 8, "AutomationFraternity",
'True or False dependening on the file availability.
Function Temp()
Dim fso,x,y,str
Dim aResult(3)
X=5
Y=8
Str = "AutomationFraternity"
'Object can be of any type of Object:
' Fso, Dictionary, XML, or QTP 'hierarchy object
'Set oBrowser = Browser("title:=.*").Page("name:=.*)
Set fso = CreateObject("Scripting.FileSystemObject")
aResult(0) = x
aResult(1) = y
aResult(2) = str
Set aResult(3) = fso
Temp= aResult
End Function

Click on 6Th link in a webpage

Using child objects

how to maximize the browser in qtp without using sendkeys


hWindow = ie.HWND ' Get the Browser Handle
Window ("hwnd:="&hWindow).Maximize

Set wshShell = CreateObject("WScript.Shell")


'Need something here to set focus on the browser(.click or something)
wshShell.SendKeys "% " 'the "alt" % and the character it is modifying should be in
same string
wait 1 'could tweak this, needs some time for the dialog to open
wshShell.SendKeys "x" ' this is a separate second command

1: Maximizing a Browser
Dim hwnd, isMaximized, isMaximizable
'Find the handle for the Browser window
hwnd = Browser("CreationTime:=0").Object.HWND
'Check if the Browser is already maximized or not
If Window("hwnd:=" & hwnd).GetROProperty("maximized") = True Then
isMaximized = True
Else
isMaximized = False
End If
'Check if the Browser is maximizable or not
If Window("hwnd:=" & hwnd).GetROProperty("maximizable") = True Then
isMaximizable = True
Else
isMaximizable = False
End If
'Maximize the browser window if it is not already maximized and is maximizable
If isMaximized = False and isMaximizable = True Then
Window("hwnd:=" & hwnd).Maximize
End If
2: Minimizing a Browser
Dim hwnd, isMinimized, isMinimizable
'Find the handle for the Browser window
hwnd = Browser("CreationTime:=0").Object.HWND
'Check if the Browser is already minimized or not
If Window("hwnd:=" & hwnd).GetROProperty("minimized") = True Then
isMinimized = True
Else
isMinimized = False
End If
'Check if the Browser is minimizable or not
If Window("hwnd:=" & hwnd).GetROProperty("minimizable") = True Then
isMinimizable = True
Else
isMinimizable = False
End If
'Minimize the browser window if it is not already minimized and is minimizable
If isMinimized = False and isMinimizable = True Then
Window("hwnd:=" & hwnd).Minimize
End If

Use HWND with Descriptive Programming for Maximizing/Minimizing a Browser In


this example, the browser properties are not stored in Object Repository, but are taken
using Descriptive Programming.

Dim oIE

2
3

'Create an object of Internet Explorer type

Set oIE= CreateObject("InternetExplorer.Application")

oIE.visible = True

oIE.navigate "http://www.automationrepository.com"

7
8

'Maximize the Browser Window

Window("hwnd:=" & oIE.HWND).Maximize

10
11

'Minimize the Browser Window

12

Wait(2)

13

4:

Window("hwnd:=" & oIE.HWND).Minimize

Use

of

SystemUtil.Run In

this

example,

the

browser

will

be

opened

maximized/minimized mode.

1
2
3
4
5
6
7

Dim mode_Maximized, mode_Minimized


mode_Maximized = 3 'Open in maximized mode
mode_Minimized = 2 'Open in minimized mode

'Open browser in maximized and minimized mode


SystemUtil.Run "iexplore.exe", "http://www.automationrepository.com", ,
,mode_Maximized
SystemUtil.Run "iexplore.exe", "http://www.automationrepository.com", ,
,mode_Minimized

in

Use of WScript.Shell RunThis example uses WScript.Shell to open a new browser in


maximized/minimized mode.

1
2
3
4
5
6
7
8

Dim WshShell, mode_Maximized, mode_Minimized


mode_Maximized = 3 'Open in maximized mode
mode_Minimized = 2 'Open in minimized mode

Set WshShell = CreateObject("WScript.Shell")


WshShell.Run "iexplore.exe http://www.automationrepository.com", mode_Maximized,
False
WshShell.Run "iexplore.exe http://www.automationrepository.com", mode_Minimized,
False
Set WshShell = Nothing

without using descriptive and OR how to a link on a link in qtp

You can just palce page check point on that page,it will
give you the details like number of images ,number of links
etc in the page

One link is invisible in webpage how do you make the qtp identify that object ?

Regular expression to match all valid email addresses


^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$

3different ways of Create a Random Number:


Many a times you would come across the need to create Random Numbers in your script.
And this random number requirement would come in different flavors you might need to
create a random number of a certain length, or you might want a random number within a
specific range, or you might just need any random number without worrying about the
range or number length. Whatever be your need, the below mentioned 3 methods should
help you find a solution. :)

1. Create a Random Number having a Fixed Length


I have created a VBScript function that should help you find a random number of any length
you

want.

'===============================================
'Function

to

Create

Random

Number

of

Any

Length

'===============================================
Function fnRandomNumber(LengthOfRandomNumber)

Dim sMaxVal

Dim iLength

'Find

sMaxVal

the

maximum

For iL

iLength

value

for

sMaxVal

= ""

the

LengthOfRandomNumber

given

number

of

digits

to

iLength

sMaxVal

& "9"

Next
sMaxVal

= Int(sMaxVal)

'Find

Random

Value

Randomize
iTmp

= Int((sMaxVal

'Add

Trailing

* Rnd)

Zeros

1)

if

required

iLen

= Len(iTmp)

fnRandomNumber

iTmp

(10

^(iLength

End

iLen))

Function

'==================

End

Function

=================

To use this function in your script, all you have to do this call this function with the lenght of
the random number you want. Example to get a random number of 6 digits, you can
writemyRandomNum = fnRandomNumber(6)

2. Create a Random Number Within a Specific Range


The first example showed how to create a random number of a fixed size. But what if you
need a random number within a specific range? In this second function, all you have to do is
to specify the maximum and minimum value. The function would return a value that lies in
between the range you specified.

'===========================================================
'Function

to

Create

Random

Number

within

'===========================================================
Function fnRandomNumberWithinRange(MinimumRange, MaximumRange)

specified

range

Dim iMax

iMax

MaximumRange

Dim iMin

iMin

MinimumRange

'Create

Random

Number

within

the

Range

Randomize
fnRandomNumberWithinRange

Int(((iMax

iMin)

End
'========================

* Rnd)

iMin)

Function
End

Function

=====================

Calling the above function as iRandomNum = fnRandomNumberWithinRange(1200,


1500)would return a random number between 1200 & 1500.

3. Create a Random Number with DateTime Stamp


This method doesnt use the Randomize & Rnd functions to create a random number.
Instead it uses the Date & Time combination to come up with a unique number. One
advantage of this method is that here you can be rest assured that whatever number you
create using this method, it would never be repeated because the combination of date &
time is always unique.

'===========================================================
'Function to Create a Random Number with DateTime Stamp
'===========================================================
Function fnRandomNumberWithDateTimeStamp()

'Find out the current date and time


Dim sDate : sDate = Day(Now)
Dim sMonth : sMonth = Month(Now)
Dim sYear : sYear = Year(Now)
Dim sHour : sHour = Hour(Now)
Dim sMinute : sMinute = Minute(Now)
Dim sSecond : sSecond = Second(Now)

'Create Random Number


fnRandomNumberWithDateTimeStamp = Int(sDate & sMonth & sYear & sHour & sMinute & sSecond)

End Function
'======================== End Function =====================

I hope that the above 3 methods would have helped you find the solution to your problem.
If you have any other way to create Random Numbers, please do share it with all the
readers using the comment

How to generate the random number in QTP ?


QTP supports the function called Rnd that generates random value between 0 and 1.
rnd function takes 1 input parameter which acts as a seed to generated further random numbers in
sequence.
To initialize the seed with system timer, you can use below statement.
Randomize

To generate the random integers we can use below statement.


Method 1
min = 1
max = 100
Randomize
RandomInt1= (Int((max-min+1)*Rnd+min))
RandomInt2= (Int((max-min+1)*Rnd+min))
print RandomInt1 'print the first random integer between 1 and 100.
print RandomInt2 ' print the second random integer between 1 and 100.

Method 2
x=RandomNumber (0,100)
print x

This is how we can generate random numbers in QTP

RandomNumber Object - Generate Random Numbers

'###############################################
'
RandomNumber Object
'###############################################
' Purpose:- Used to generate Random Numbers between specific range
'Syntax: RandomNumber(ParameterNameOrStartNumber [,EndNumber])
'The below script prints 5 random numbers between 1 and 10
For iStart=1 to 5
print RandomNumber(1,10)
Next
'**********************************************
'Generating Random Numbers with rnd function
'**********************************************
'Formulae:-

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

upperbound=10
lowerbound =1
For iStart=1 to 5
print Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Next
'Here rnd function generates a float value
'Int function return integer value
Posted by Qtp Sudhakar at 3:56 AM

Different ways to lanch the application with out Systemutil.run

1. SystemUtil.Run
SystemUtil.Run ( FileName, Parameters, Path, Operation )

FileName The name of the file you want to run.

Parameters (optional) If the specified FileName is an executable file, use the


Parameters argument to specify any parameters to be passed to the application.

Path(optional) The default directory of the application or file.

Operation(optional) The action to be performed. If this argument is blank (), the open
operation is performed. The following operations can be specified for the operation argument of the
SystemUtil.Run method:

open Opens the file specified by the FileName parameter. The file can be an
executable file, a document file, or a folder. Non-executable files are open in the associated
application.

edit Launches an editor and opens the document for editing. If the FileName
argument does not specify an editable document file, the statement fails.

explore Explores the folder specified by the FileName argument.

find Initiates a search starting from the specified folder path.

print Prints the document file specified by the FileName argument. If the specified
file is not a printable document file, the statement fails.
Example Usage:
SystemUtil.Run "C://Program Files/Internet Explorer/IEXPLORE.EXE"

2. InvokeApplication
This command is now mainly used for the backward compatibility ie to use with the lower versions
(below QTP 6.0) of QTP.
InvokeApplication("Full URL as Parameter")
Example Usage:
InvokeApplication "C://Program Files/Internet Explorer/IEXPLORE.EXE
http://www.yahoo.com"

3. VBscript to invoke application


1.

Create a WScript.shell object.

2.

Use the run object to launch the application. If the path to your executable contains spaces,
use Chr(34) to ensure the path is contained within double quotes.

3.

When done, set the shell object to nothing to release it.


Example:

1. Dim oShellSet oShell = CreateObject ("Wscript.shell")'


2. 'Example 1 - run a batch file:
3. oShell.run "F://jdk1.3.1/demo/jfc/SwingSet2.bat"
4. 'Example 2 - run a Java jar file:
5. oShell.run "java -jar
F://jdk1.3.1/demo/jfc/SwingSet2/SwingSet2.jar"
6. 'Example 3 - launch Internet Explorer:
7. oShell.Run Chr(34) & "C://Program Files/Internet
Explorer/IEXPLORE.EXE" & Chr(34)
8. Set oShell = Nothing

4. Trivial but useful method


If nothing works out you might try this
Use the Start -> Run dialog of Windows.
1.

Add the Windows Start button to the Object Repository using the Add Objects button in
Object Repository dialog.

2.

Open the Run dialog (Start -> Run), and learn the Open edit field and the OK button into
the Object Repository.

3.

Switch to the Expert View, and manually add the lines to open the Run dialog.
Example:
Window("Window").WinButton("Button").ClickWindow("Window").Type("R")

4.

Manually enter the lines to enter the information to launch the application, and click the
OK button of the Run dialog.
Example:
Dialog("Run").WinEdit("Open:").Type "C://Windows/System32/notepad.exe"
Dialog("Run").WinButton("OK").Click
If you want to keep track of further articles on QTP. I recommend you to subscribe via RSS Feed.
You can also subscribe by Email and have new QTP articles sent directly to your inbox.
Please use QTP forum for posting QTP questions.

Creating the object


Set oshell=createObjct(Wscript.shell)
Oshell.run cmd/notepad.winword
It also for.exe files.

VBscript delete files and


folders older than X days
Const strPath = "D:\My Backups"
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call Search (strPath)
' Comment out below line if you'd like to use this script in windows schedule
task
WScript.Echo"Done."
Sub Search(str)
Dim objFolder, objSubFolder, objFile
Set objFolder = objFSO.GetFolder(str)
For Each objFile In objFolder.Files
' Use DateLastModified for modified date of a file
If objFile.DateCreated < (Now() - 50) Then
objFile.Delete(True)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Search(objSubFolder.Path)
' Files have been deleted, now see if the folder is empty.
If (objSubFolder.Files.Count = 0) Then
objSubFolder.Delete True
End If
Next
End Sub

one popup message is coming sometimes and need to capture messag and continue.how willdo it
in qtp allinterview.com

How to clear the array in qtp

Sub EraseArray(ByRef arr)


For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
If IsObject(arr(i, j)) Then
Set arr(i, j) = Nothing
Else
arr(i, j) = Empty
End If
Next
Next
End Sub

Or like this, if you don't want to set fields containing objects to Nothing:
Sub EraseArray(ByRef arr)
For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
arr(i, j) = Empty
Next
Next
End Sub

-How to handle the scenario when page is not getting loaded and because of the
script getting failed?
-Read str1 and find each character in str2,and remove the matched character in
str2.Print str2 characters which are left?
-How to validate below scenario:
100,2 then 200.. In appln there is one weblist and webedit(which is
readonly)and weblist contains 1 to 100 If we select 1 editbox dispalys
-In appln None of the fields are mandatory,click on submit blank reg takes
place.How to validate the fields?
- How to find latest modified file in qtp
option explicit

dim fileSystem, folder, file


dim path
path = "C:\test"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateLastModified > dateadd("h", -24, Now) then
'whatever you want to do to process'
WScript.Echo file.Name & " last modified at " & file.DateLastModified
end if
next

How to find Data Type of a Variable?


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

1.
2.

Vartype
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
Datatype

Description

vbEmpty

Empty (uninitialized)

vbNull

Null (no valid data)

vbInteger

Integer

vbLong

Long integer

vbSingle

Single-precision floating-point
number

vbDouble

Double-precision floating-point
number

vbCurrency

Currency

vbDate

Date

vbString

String

vbObject

Automation object

10

vbError

Error

11

vbBoolean

Boolean

12

vbVariant

Variant (used only with arrays


of Variants)

13

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

Object variable that doesn't yet refer to an


object instance

Error

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
-Challenges in cross Browser Testing?
-Useof SetTo Property
-Recordset object carries null values,How to handlthe scenario that no further
process done in the testrun?
-Why use dictionary object?when dynamic array can be used for the same
purpose?
-what is REM function,What is Option Explicit,when we use exit Sub()
-Difference between for loop and Foe Each
-

Dot Net Factory - Basics


Dot Net Factory is a utility object that enables QTP scripting to directly access
methods and properties of Dot Net Object

Because of this method, QTP stands at no limit in its capability. Using Dot Net
Factory, QTP can access the Dot Nets static methods and properties of a class that
does not have instance constructor and also user defined custom dot net classes.

Syntax of Dot Net Factory

DotNetFactory.CreateInstance (TypeName [,Assembly] [,args])


TypeName The Full Name of the object Type. E.g. System.DateTime
Assembly This is optional. You need to pass the assembly for type. If the assembly
is preloaded in the registry, you do not need to enter it. If you do not pass this
argument, QTP assumes that the assembly is resident in memory. If QuickTest does
not find the assembly, an error message is displayed during the run session.

Args This is also optional, You need to pass the arguments for typename you
specified or for assembly (if any)
Let us go with examples to get a clear idea,
Example 1:

Working with Dot net Date Parser


Dim dSysDate , objDate
Set dSysDate = Dotnetfactory.CreateInstance(System.DateTime) ' Creating an
object for Dot Net Component System.DateTime
Set objDate = dSysDate.Parse(Mon, 9 Sep 2013)
strDate = objDate.Day & / & objDate.Month & / & objDate.Year
msgbox strDate
Set dSysDate = Nothing
Set objDate = Nothing
The output will be 09/09/2013.
Example 2:
Simple user defined forms
The below example deals with creating a simple Dot net form with a button, text box and
label using dot net component System.Windows.Forms

Creates a Form
Set objFrm = DotNetFactory.CreateInstance(System.Windows.Forms.Form,
System.Windows.Forms)
Creates a Button
Set objBtn = DotNetFactory.CreateInstance(System.Windows.Forms.Button,
System.Windows.Forms)
Created a Text Box
Set objEdt = DotNetFactory.CreateInstance(System.Windows.Forms.TextBox,
System.Windows.Forms)
intx=60
inty=30
Creates an object to system drawing point to draw a form and to get the locations(X, Y) for
the controls
Set objpnt =
DotNetFactory.CreateInstance(System.Drawing.Point,System.Drawing,intx,inty)
Creates a label
Set objlbl=
DotNetFactory.CreateInstance(System.Windows.Forms.Label,System.Windows.Forms)
Configuring the label
objlbl.Text=Enter Password
objlbl.Location= objpnt
Adding the label in Form
objFrm.Controls.Add(objlbl)
objpnt.Y=CInt(objlbl.Height)+40
objEdt.Location= objpnt
objEdt.UseSystemPasswordChar=true To set the password character From system
objFrm.Controls.Add(objEdt) Adding the Text box in Form
objBtn.Text=Close
objpnt.Y=Cint(objpnt.Y)+CInt(objEdt.Height)+20
objBtn.Location=p1
objFrm.CancelButton= objBtn Adding a button as cancel button in form
objFrm.Controls.Add(objBtn)
objFrm.Text=Dot Net Factory Dialog Box
objFrm.StartPosition=CenterScreen
objForm.ShowDialog Showing the designed form
The above mentioned method is suitable for simple forms and may look little complex when
we are creating a complex form or form with more controls.
Most of the time we prefer IDE based design for designing a form rather then creating them
using code, so lets look into the IDE based form design in my next article on Dot Net
Factory.

What is DotNetFactory?

DotNetFactory is an object. It enables you to create an instance of a .NET object, and


access its methods and properties.
You can also use DotNetFactory to access the static methods and properties of a class that
does not have an instance constructor, for example, System.Environment.
DotNetFactory is a part of Utility Object. You do not need to have .NET Add-in installed in
order to use this.
Example 1 of DotNetFactory
We will start with a simple example as shown in the QTP Help.
Set var = DotNetFactory.CreateInstance("System.Windows.Forms.Form",
"System.Windows.Forms")
var.Show
wait 5
var.Close
[See the screenshot below of the above code run]
In the above example we are using CreateInstance method of DotNetFactory object. We are
using CreateInstance method to create an instance of a blank Windows form object, display
the form on screen, and then close it after two seconds. Show and Close method simply
show and close the form respectively.
We are using System.Windows.Forms namespace and Form class in the first line of the code
above. A Form is a representation of any window displayed in your application. The Form
class can be used to create standard, tool, borderless, and floating windows. You can also
use the Form class to create modal windows such as a dialog box.
CreateInstance Syntax
DotNetFactory.CreateInstance (TypeName [,Assembly] [,args])
TypeName: The full name of the object type e.g. System.Windows.Forms.Form
Assembly: System.Windows.Forms (in System.Windows.Forms.dll) - An Assembly is a
logical unit of code, Assembly physically exist as DLLs or EXEs, One assembly can contain
one or more files. Source
Args: The required arguments, if any.

Example 2 of DotNetFactory
Set var = DotNetFactory.CreateInstance("System.Environment")
msgbox var.CurrentDirectory
[See the screenshot below of the above code run.]
Above we are creating an instance of System Environment object. In the second line we are
using the CurrentDirectory property which gets or sets the fully qualified path of the current
working directory.
Similarly you can use:
msgbox var.Username
msgbox var.OSVersion
msgbox var.MachineName etc.
Few Methods and Properties can be found here.

Example 3 of DotNetFactory
Set var = DotNetFactory.CreateInstance("System.IO.File",
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll")
x= var.readalltext ("c:\a.txt")
msgbox x
File Class of System.IO namespace provides static methods for the creation, copying,
deletion, moving, and opening of files etc.
The above example should also work fine without the assembly path as below:
Set var = DotNetFactory.CreateInstance("System.IO.File")
x= var.readalltext ("c:\a.txt")
msgbox x
ReadAllText: Opens a text file, reads all lines of the file, and then closes the file. It returns
a string containing all lines of the file.
Example 4 of DotNetFactory
Set var = DotNetFactory.CreateInstance("System.IO.File")
set x= var.opentext ("c:\a.txt")
Do
s=x.readline()
If (s="") Then
Exit do
End If
msgbox s
Loop
OpenText Method opens an existing UTF-8 encoded text file for reading. It returns a value

of type StreamReader. ReadLine Method of StreamReader object reads a line of characters


from the current stream and returns the data as a string.
Example 5 of DotNetFactory
Set my_stack = DotnetFactory.CreateInstance("System.Collections.Stack")
my_stack.push("one")
my_stack.push("two")
my_stack.push("three")
msgbox my_stack.count
msgbox my_stack.pop
Stack Class represents a simple last-in-first-out collection of objects.
Push inserts an object at the top of the Stack.
Pop removes and returns the object at the top of the Stack.
See all classes represented by System.Collections Namespace here.
Example 6 of DotNetFactory
Set my_array = DotnetFactory.CreateInstance("System.Collections.ArrayList")
my_array.add("Hello")
my_array.add("World")
my_array.add("!")
msgbox my_array.count
For i = 0 To my_array.Count - 1
a=my_array.Item(cint(i))
msgbox a
Next
ArrayList Class of System.Collections namespace implements the IList (Represents a nongeneric collection of objects that can be individually accessed by index.) interface using an
array whose size is dynamically increased as required.
You can use the CInt function to provide internationally aware conversions from any other
data type to an Integer subtype.
More on ArrayList members here.
Example 7 of DotNetFactory
Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )
sb.Append "sachin"

sb.Append "ii"
sb.Replace "i", "x"
msgbox sb.ToString
msgbox sb.Length
StringBuilder Class represents a mutable (Changeable) string of characters.
Append (String) Method of StringBuilder class appends a copy of the specified string to
the end of this instance. It returns a reference to this instance after the append operation
has completed.
Replace replaces all occurrences of a specified character or string in this instance with
another specified character or string.
ToString Method of StringBuilder class Converts the value of this instance to a String. It
returns a string whose value is the same as this instance.
Above ii is being appended to sachin to form sachinii and then Replace replaces all i's in
sachinii to x.

Example 8 of DotNetFactory

Set dt = DotNetFactory.CreateInstance( "System.DateTime" )


msgbox dt.now
Set sb = DotNetFactory.CreateInstance( "System.DateTime" )
set dt= sb.now
msgbox dt.day
msgbox dt.month
msgbox dt.year
DateTime Structure of System Namespace represents an instant in time, typically
expressed as a date and time of day.
Now property gets a DateTime object that is set to the current date and time on computer,
expressed as the local time.
Day gets the day of the month represented by this instance.
Month gets the month component of the date represented by this instance.
Year gets the year component of the date represented by this instance.
Set object = DotNetFactory.CreateInstance( "System.DateTime", ,year, month, day, hour,
minute, second, millisecond )
Set two = DotNetFactory.CreateInstance( "System.DateTime", ,1998, 9, 1, 16, 30, 22, 5 )
msgbox two.tostring()

Set object = DotNetFactory.CreateInstance( "System.DateTime", ,year, month, day, hour,


minute, second)
Set tme = DotNetFactory.CreateInstance( "System.DateTime", ,1980, 8, 15, 21, 30, 9)
msgbox tme.tostring()

More on DateTime members here.


Example 9 of DotNetFactory
format = "{0} Current Date & Time is {1}"
Set TDT = DotNetFactory.CreateInstance( "System.DateTime" )
Set SB = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )
SB.AppendFormat format, "Hello,", TDT.now
Msgbox SB.ToString()
format is a variable. AppendFormat appends - Hello (in the {0}th place) and TDT.Now
which is current date & time (in the {1}st place) - to the string contained in format.

dotnetfactory object in QTP


var_CreateInstance = DotNetFactory.CreateInstance("System.Environment")
msgbox var_CreateInstance.CurrentDirectory
Dim SystemDate , oDate
Set SystemDate = Dotnetfactory.CreateInstance("System.DateTime")

Set oDate = SystemDate.Parse("Fri, 9 Oct 2009")


FormattedDate = oDate.Day & "/" & oDate.Month & "/" & oDate.Year
msgbox FormattedDate
Set SystemDate = Nothing
Set oDate = Nothing The .NET SortedList class provides a hash table with automatically sorted key/value
pairs.
The following code creates a SortedList and populates it with some key/value pairs:Set objSortedList =
Dotnetfactory.CreateInstance ( "System.Collections.Sortedlist" )
objSortedList.Add "First", "Hello"
objSortedList.Add "Second", ","
objSortedList.Add "Third", "world"
objSortedList.Add "Fourth", "!"
For i = 0 To objSortedList.Count - 1
WScript.Echo objSortedList.GetKey(i) & vbTab & objSortedList.GetByIndex(i)
Next
' this code creates and populates an ArrayList
Set myArrayList = CreateObject( "System.Collections.ArrayList" )
myArrayList.Add "F"
myArrayList.Add "B"
myArrayList.Add "D"
myArrayList.Add "C"
' [1] add the new element to the ArrayList
myArrayList.Add "Z"
' [2] sort the ArrayList
myArrayList.Sort

And how about deleting an element?


In an array you would need to "shift" the elements to fill the gap and then ReDim the array again.
In an ArrayList you would use either myArrayList.Remove "element_value" or myArrayList.RemoveAt
"element_index".

DotnetFactory Object - Creating .Net Forms Using QTP


'###############################################
'
DotNetFactory Object
'###############################################

'Purpose - To create an instance of a .NET object, and access its methods and
properties.
'
We can create forms where the user can interact with them and give some
input in run time
Set MainForm = DotNetFactory.CreateInstance("System.Windows.Forms.Form",
"System.Windows.Forms")
Set TextField = DotNetFactory.CreateInstance("System.Windows.Forms.TextBox",
"System.Windows.Forms")
Set Button = DotNetFactory.CreateInstance("System.Windows.Forms.Button",
"System.Windows.Forms")
Set objPosition =
DotNetFactory.CreateInstance("System.Drawing.Point","System.Drawing",x,y)
'Assign Text Field Details
objPosition.X = 100
objPosition.Y = 100
TextField.Location = objPosition
TextField.Width = 100
'Assign Button Details
objPosition.X = 100
objPosition.Y = 130
Button.Location = objPosition
Button.Text = "Close"
'Add Text Field and Button to Main Form
MainForm.Controls.Add TextField
MainForm.Controls.Add Button
MainForm.CancelButton = Button
'Show Form
MainForm.ShowDialog
Msgbox TextField.Text
Set
Set
Set
Set

TextField = Nothing
Button = Nothing
objPosition = Nothing
MainForm = Nothing

Using DotNetFactory object you can access .NET base classes into your QTP scripts. This also supports
using DLLs compiled from any .NET language. This features works on .NET Interop which means you can
call .NET components in COM environment and vice versa.
Using ArrayList Class
Here is an example where we have a test scenario which requires sorting and searching of an array of
values. We will use ArrayList class from System.Collections namespace. Collections namespace has
variety of classes like Array, HashTable, Stack, LinkedList etc.

ArrayList class is enriched with various ready to use methods for Sorting, Reversing, and Searching
items.

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
38
39
40
41
42
43

'//Create an instance of System.Collections.ArrayList using DotnetFactory.CreateInstan


Set myList = DotnetFactory.CreateInstance("System.Collections.ArrayList")
'//Add items to the List Array
myList.Add("American")
myList.Add("Ukrainian")
myList.Add("bElarusian")
myList.Add("Indian")
myList.Add("123")
myList.Add("$@%^%@")
'//ArrayList.Capacity/ArrayList.Count shows the number of elements it have
Print "Capacity of ArrayList is: " & myList.Capacity
Print "Count of ArrayList is: " & myList.Count
'//ArrayList adds empty memory locations when new items are added to the list
'//using TrimToSize you can remove these empty locations from the list
myList.TrimToSize
'//SORTING
'//You can sort the contents of an ArrayList using Sort method, for Ascending sort:
myList.Sort
'//For displaying array contents in a String
strMsg = ""
For intCnt = 0 To myList.Count - 1
strMsg = strMsg & myList.Item(CInt(intCnt)) & vbCrLf
Next
Print "Sorted Array List: Asecending" & vbCrLf & strMsg

'//You can Sort an array Descending with Reverse method. But first you need to sort th
'//using Sort method
myList.Reverse
'//For displaying array contents in a String
strMsg = ""
For intCnt = 0 To myList.Count - 1
strMsg = strMsg & myList.Item(CInt(intCnt)) & vbCrLf
Next
Print "Sorted Array List: Descending" & vbCrLf & strMsg

'//SEARCHING
'//You can search an item using IndexOf and BinarySearch method. These method return z
'//of an item for its first occurrence

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

Print "Indian item found at: " & myList.IndexOf("Indian") & vbCrLf & strMsg,,"IndexOf
Print "indian item found at: " & myList.IndexOf("indian") & vbCrLf & strMsg,,"IndexOf
'//For BinarySearch ArrayList should be sorted in Ascending Order
myList.Sort
'//For displaying array contents in a String
strMsg = ""
For intCnt = 0 To myList.Count - 1
strMsg = strMsg & myList.Item(CInt(intCnt)) & vbCrLf
Next

Print ,"Binary Search: " & vbCrLf & "bElarusian item found at: " & myList.BinarySearch(
& strMsg
Print ,"Binary Search: " & vbCrLf & "Belarusian item found at: " & myList.BinarySearch(
& strMsg
'//ArrayList.Contains method searches for given item and returns True/False
Print myList.Contains("Indian")
Set myList = Nothing

This approach is much faster and reliable than writing code our own code.
Using Clipboard Object
You can access Clipboard object using System.Windows.Forms.Clipboard class. Here is an example
showing how to Clear, Set and Get contents from Clipboard.

1
2
3
4
5
6
7
8
9
10
11
12
13

'//This is not supported in 8x versions


Set oClip =
DotNetFactory.CreateInstance("System.Windows.Forms.Clipboard")
'//Clears the Clipboard
oClip.Clear
'//Sets sample text on Clipboard
oClip.SetText "DotNetFactory Rocks!!"
'//Retrieves text from Clipboard
strContents = oClip.GetText

14

Print strContents

File Input/Output
Using System.IO.File class you can create, read and write to files. Here is an example on writing to and
reading from a file.

1
2
3
4
5
6
7
8
9
10
11

'//This is not supported in 8x versions


Set objFile = DotNetFactory.CreateInstance("System.IO.File")
'//Creates a new file with given text
objFile.WriteAllText "C:\Test.txt","DotNetFactory Rocks!!"
'//Retrieves text from given file
strContents = objFile.ReadAllText("C:\Test.txt")
Print strContents

This way you can use 100s of classes available in .NET Framework in your QTP Scripts.

You might also like