QTP World
QTP World
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
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
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.
set sqlconnection=createobject("ADODB.connection")
set sqlrecordset=createobject("ADODB.recordset")
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
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"
Using Trim(str,3)
Using mid(str,1,3)
3.
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.
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
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
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
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
webutil.DeleteCookies
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
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
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
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
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?
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?
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
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.
if val="123" then
msgbox "the row is "&i
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
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
SystemUtil.CloseProcessByName "IEXPLORE"
'It will close all Browsers with all dependant popup
windows.
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,
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.
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...
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"
Base filter properties,the most fundamental properties of a particular test object class,whose values
cannot be changed.
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.
set a = description.create
a("micclass").value = "webedit"
set ch_obj = browser("").page("").childobjects(a)
msgbox ch_obj.count
rcnt=Browser().Page().webTable().rowcount
ccnt=Browser().Page().webTable().columncount(2)
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 .
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
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.
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.
ExecuteFile "File"
LoadFunctionLibrary "Path of File"
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
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
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
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
MsgBox File1 & " and " & File2 & " " &
Else
MsgBox File1 & " and " & File2 & " " &
End If
"are identical."
"are NOT identical."
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
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.
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)
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)
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
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)
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.
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
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
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
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.
If page opens
objxls3.sheet(1).cells(1,1) = "PASS"
else
objxls3.sheet(1).cells(1,1) = "FAIL"
Endif
webutil.DeleteCookies
If var.name<>"index.dat" Then
var.delete
End If
Next
Set WshNetwork=Nothing
Set fso=Nothing
End Sub
statement1;
statement2;
.
.
}
While (condition)
Statements following the loop
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
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
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.
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
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
Objectheirarchy.CaptureBitmap "path"
navigation:
File Menu -> Settings -> Run Tab -> Choose the required
action from the "Whenever an error occurs during run
session" drop down list box.
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
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)
For Ques 1
Browser().page().webtable().childitem
(2,3,"WebButton",0).Click
For Ques 2
strname=Browser().page().webtable().GetCellData(2,3)
msgbox strname
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)
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
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
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()
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")
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
MouseClick x, y, button
MouseDblClick x, y, button
DragAndDrop x, y, dropx,
dropy, button
PressKey key
MouseDown x, y, button
MouseUp x, y, button
KeyDown key
KeyUp key
Type a string.
165
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
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
1)
(Use
Sort
Sorting)
the
input
array.
count
array)
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)
(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>
Method
(Make
two
equations)
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.
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>
{
int xor1;
int set_bit_no;
int i;
*x = 0;
*y = 0;
xor1 = arr[0];
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.
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.
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.
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.
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.
- 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.
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
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
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
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: "&fileName1,"CSV"
Elseif UCase(fileNameArr(ubound(fileNameArr))) = "XLS" or
UCase(fileNameArr(ubound(fileNameArr))) = "XLSX" then
reporter.ReportEvent micPass,"This is an Excel file:"&fileName1,"Excel"
Else
reporter.ReportEvent micFail,"This is not CSV or Excel file:"&fileName1,"Error"
End If
next
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.
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.
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
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
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.
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.
At the end of Run, all the dynamically loaded libraries are unloaded.
<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
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
Dim oIE
2
3
oIE.visible = True
oIE.navigate "http://www.automationrepository.com"
7
8
10
11
12
Wait(2)
13
4:
Use
of
SystemUtil.Run In
this
example,
the
browser
will
be
opened
maximized/minimized mode.
1
2
3
4
5
6
7
in
1
2
3
4
5
6
7
8
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 ?
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)
'===========================================================
'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
=====================
'===========================================================
'Function to Create a Random Number with DateTime Stamp
'===========================================================
Function fnRandomNumberWithDateTimeStamp()
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
Method 2
x=RandomNumber (0,100)
print x
'###############################################
'
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:-
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
1. SystemUtil.Run
SystemUtil.Run ( FileName, Parameters, Path, Operation )
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.
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"
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.
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.
one popup message is coming sometimes and need to capture messag and continue.how willdo it
in qtp allinterview.com
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
1.
2.
Vartype
Typename
Return Value
Sub
Datatype
Description
vbEmpty
Empty (uninitialized)
vbNull
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
13
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
Single
Double
Currency
Currency value
Decimal
Decimal value
Date
String
Boolean
Empty
Unitialized
Null
No valid data
Generic object
Unknown
Nothing
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.
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.
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:
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?
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
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
'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
'//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
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 way you can use 100s of classes available in .NET Framework in your QTP Scripts.